Error Checking and Handling

Error Checking and Handling

We'll first cover error checking and handling, as they are vital to writing a successful Winsock application. It is actually common for Winsock functions to return an error; however, there are some cases in which 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. On the flip side of WSAGetLastError, there is WSASetLastError, which allows you to manually set error codes that WSAGetLastError retrieves.

The following program demonstrates how to construct a skeleton Winsock application based on the discussion so far:

#include <winsock2.h> void main(void) {    WSADATA wsaData;    // Initialize Winsock version 2.2    if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)    {       // NOTE: Since Winsock failed to load we cannot use        // WSAGetLastError to determine the specific error for       // why it failed. Instead we can rely on the return        // status of WSAStartup.       printf("WSAStartup failed with error %d\n", Ret);       return;    }    // Setup Winsock communication code here     // When your application is finished call WSACleanup    if (WSACleanup() == SOCKET_ERROR)    {       printf("WSACleanup failed with error %d\n", WSAGetLastError());    } }

Now we are ready to describe how to set up communication using a network protocol.



Network Programming for Microsoft Windows
Network Programming for Microsoft Windows (Microsoft Professional Series)
ISBN: 0735605602
EAN: 2147483647
Year: 2001
Pages: 172
Authors: Anthony Jones

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net