WSAGetLastError Function
The WSAGetLastError
function retrieves the extended error code for the calling thread. This function is used to obtain detailed error information for Windows Sockets API functions.
Syntax
int WSAGetLastError(void);
Return Value
- Return value
- The return value is an integer that represents the extended error code. If the last Winsock function call was successful, the return value is zero. Otherwise, it is one of the Winsock error codes.
Remarks
Most Windows Sockets API functions set an extended error code when they fail. The WSAGetLastError
function is used to retrieve this code. It is important to call WSAGetLastError
immediately after a Winsock function fails, as subsequent Winsock calls might overwrite the error code.
The extended error codes are defined in the winsock2.h
header file as constants starting with WSAE
. A comprehensive list of these error codes can be found in the Winsock documentation.
Note: The
WSAGetLastError
function is a synonym for WSAGetLastError
. You can use either name.
Example
Retrieving an Error Code
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
std::cerr << "WSAStartup failed: " << iResult << std::endl;
return 1;
}
// Attempt a connection that will likely fail
SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
int errorCode = WSAGetLastError(); // Or WSAGetLastError()
std::cerr << "Socket creation failed. Error code: " << errorCode << std::endl;
// You can then use a lookup mechanism or switch statement to interpret errorCode
WSACleanup();
return 1;
}
// Example of a failing connect call (assuming 127.0.0.1:1 is not listening)
sockaddr_in clientService;
clientService.sin_family = AF_INET;
clientService.sin_addr.s_addr = inet_addr("127.0.0.1");
clientService.sin_port = htons(1);
iResult = connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));
if (iResult == SOCKET_ERROR) {
int errorCode = WSAGetLastError(); // Get the specific error code
std::cerr << "Connection failed. Error code: " << errorCode << std::endl;
// Example: WSAECONNREFUSED (10061) is a common error for failed connections
if (errorCode == WSAECONNREFUSED) {
std::cerr << "Error detail: Connection refused." << std::endl;
}
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// If connection was successful (unlikely in this example)
std::cout << "Connection successful." << std::endl;
closesocket(ConnectSocket);
WSACleanup();
return 0;
}