Retrieves the error code from the most recent Windows Sockets API call.
int getlasterror(void);
This function does not take any parameters.
int
: Returns the error code from the most recent Windows Sockets API call. A return value of 0 indicates success.The getlasterror
function retrieves the error code set by the most recent Windows Sockets API function call that failed. The error code is specific to Windows Sockets and is not the same as system error codes. It is important to call getlasterror
immediately after a Winsock function returns an error, as subsequent Winsock calls may overwrite the error code.
The following table lists some common Winsock error codes. For a complete list, refer to the Winsock header files (e.g., winsock2.h
).
Error Code | Symbolic Constant | Description |
---|---|---|
10001 | WSAHOST_NOT_FOUND |
Authoritative answer: Host not found. |
10002 | WSATRY_AGAIN |
Non-authoritative answer: Try again. |
10003 | WSANO_RECOVERY |
Non-recoverable error: Name does not exist. |
10004 | WSANO_DATA |
Valid name, no data record returned. |
10005 | WSAEINTR |
A blocking Winsock call was interrupted by a call to WSACancelBlockingCall . |
10051 | WSAENETUNREACH |
A socket operation was attempted to an unreachable network. |
10054 | WSAECONNRESET |
An existing connection was forcibly closed by the remote host. |
10061 | WSAECONNREFUSED |
Attempt to connect to a remote server failed because the actively refused it. |
The following example demonstrates how to check for and report a Winsock error.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET sock = INVALID_SOCKET;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// Attempt to create a socket (this will likely fail if not configured properly)
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET) {
int errorCode = getlasterror(); // Get the error code immediately
printf("socket failed with error: %d\n", errorCode);
// You could then look up the error code's meaning:
switch(errorCode) {
case WSAEINTR:
printf("Error: Operation interrupted.\n");
break;
case WSAENETUNREACH:
printf("Error: Network is unreachable.\n");
break;
// Add more cases for other common errors
default:
printf("Unknown Winsock error.\n");
}
WSACleanup();
return 1;
}
printf("Socket created successfully (this is unlikely in a simple example).\n");
// Clean up Winsock
WSACleanup();
return 0;
}
Client | Server | SDK |
---|---|---|
Windows XP with SP2, Windows Vista, Windows 7, Windows 8, Windows 10 | Windows Server 2003 with SP2, Windows Server 2008, Windows Server 2012, Windows Server 2016 | Windows.h |
getlasterror
)