Failing to use Function Return values

 < Day Day Up > 



This particular pitfall should be understood without question, but in many cases (even in some of the examples in this book), return values of the Sockets API functions are ignored leading to subsequent erroneous behavior by the application. Many of the BSD API functions return error indications, but some return other relevant information.

For example, consider this simple accept code snippet:

  server = socket( AF_INET, SOCK_STREAM, 0 );   ...   listen( server, SO_MAXCONN );   while ( 1 ) {     clisock = accept( server, (struct sockaddr_in *)NULL, NULL );     nread = read( clisock, buffer, MAX_BUFFER); ...

This code assumes that the client socket (clisock) returned by the accept function is a valid socket descriptor. The accept call could return an error, which would need to be dealt with very easily as:

  server = socket( AF_INET, SOCK_STREAM, 0 );   ...   listen( server, SO_MAXCONN );   while ( 1 ) {     clisock = accept( server, (struct sockaddr_in *)NULL, NULL );     if (clisock == -1) {       printf("Error on accept (%d)\$$\n", errno);     } else {       nread = read( clisock, buffer, MAX_BUFFER);   ...

A more complex example that relates to the underlying Sockets layer is provided with the send API function. The send function for stream sockets returns –1 upon error, or the number of octets that were actually sent. What this means is that if insufficient space exists for the socket’s send buffer, the function may block or enqueue what it can and then return the count of bytes that were actually enqueued. The following code snippet makes use of the return value to ensure that all data is actually written:

/* count is number of bytes to send */ written = 0; while (written < count) {     sts = send( socket, &buffer[written], (count-written), 0 );     if (sts == -1) break;     else written += sts; }

This ensures that all data is written from buffer, regardless of the chunk rate of the underlying Sockets layer.

A final point to note is that error return behavior in blocking sockets must be treated differently than in nonblocking sockets. For example, in a nonblocking socket, an error return of EAGAIN from the recv call indicates that no data currently exists to read (would need to block). Similarly, for the send call, EAGAIN indicates that the call is unable to queue to data for transmission (likely because the socket’s send buffer is full).



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

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