Error Handling

In order to provide a consistent mechanism for reporting errors and to ensure safety of Windows Sockets applications in multithreaded versions of Windows (like Windows NT), the WSAGetLastError() API was introduced as a means to get the code for the last network error on a particular thread. Under Windows 3.x, thread safety is not an issue, although WSAGetLastError() is still the appropriate way to check for extended error codes. Many functions in the Windows Sockets API set return an error code in the event that there was a problem, and rely on the application to call WSAGetLastError() to get more detailed information on the failure. The following code illustrates how an application might report an error to a user:


LPHOSTENT        host_info;
char         user_buf[MAX_BUF],    appl_buf[MAX_BUF];
.
.
.
/* Attempt to resolve hostname specified by user_buf,return meaningful */
/* message to the user in the event of an error. */

host_info=gethostbyname(user_buf);
if(host_info==NULL){
    sprintf(buf,"Windows Sockets error %d: Hostname: %s couldn't be resolved.",
         WSAGetLastError(),user_buf);
    MessageBox (hWnd,buf,"Windows Sockets Error",MB_OK);}
.
.
.

In addition to the WSAGetLastError() API, an application may choose to use the WSASetLastError() API to set a network error condition which will be returned by a subsequent WSAGetLastError() call. Obviously, any Windows Sockets calls made between a WSASetLastError() and WSAGetLastError() pair will override the code set by the WSASetLastError() call.