BSD Sockets Interface Programmer's Guide

Chapter 2 57
Using Internet Stream Sockets
Example Using Internet Stream Sockets
if (shutdown(s, 1) == -1) {
perror(argv[0]);
fprintf(stderr, “%s: unable to shutdown socket\n”,argv[0]);
exit(1);
}
/* Start receiving all the replys from the server.
* This loop will terminate when the recv returns
* zero, which is an end-of-file condition. This
* will happen after the server has sent all of its
* replies, and closed its end of the connection.
*/
while (i = recv(s, buf, 10, 0)) {
if (i == -1) {
errout: perror(argv[0]);
fprintf(stderr, “%s: error reading result\n”,argv[0]);
exit(1);
}
/* The reason this while loop exists is that there
* is a remote possibility of the above recv returning
* less than 10 bytes. This is because a recv returns
* as soon as there is some data, and will not wait for
* all of the requested data to arrive. Since 10 bytes
* is relatively small compared to the allowed TCP
* packet sizes, a partial receive is unlikely. If
* this example had used 2048 bytes requests instead,
* a partial receive would be far more likely.
* This loop will keep receiving until all 10 bytes
* have been received, thus guaranteeing that the
* next recv at the top of the loop will
* start at the begining of the next reply.
*/
while (i < 10) {
j = recv(s, &buf[i], 10-i, 0);
if (j == -1) goto errout;
i += j;
}
/* Print out message indicating the
* identity of this reply.
*/
printf(”Received result number %d\n”, *(int *)buf);
}
/* Print message indicating completion of task. */
time(&timevar);
printf(”All done at %s”, ctime(&timevar));
}