We'll first cover error checking and error handling, as they are vital to writing a successful Winsock application. It is actually common for Winsock functions to return an error; however, many times the error is not critical and communication can still take place on that socket. The most common return value for an unsuccessful Winsock call is SOCKET_ERROR, although this is certainly not always the case. When covering each API call in detail, we'll point out the return value corresponding to an error. The constant SOCKET_ERROR actually is -1. If you make a call to a Winsock function and an error condition occurs, you can use the function WSAGetLastError to obtain a code that indicates specifically what happened. This function is defined as
int WSAGetLastError (void); |
A call to the function after an error occurs will return an integer code for the particular error that occurred. These error codes returned from WSAGetLastError all have predefined constant values that are declared in either Winsock.h or Winsock2.h, depending on the version of Winsock. The only difference between the two header files is that Winsock2.h contains more error codes for some of the newer API functions and capabilities introduced in Winsock 2. The constants defined for the various error codes (with #define directives) generally begin with WSAE.