The Linux Programming Interface

(nextflipdebug5) #1

1220 Chapter 59


z Ignore the SIGPIPE signal w. This prevents the server from receiving the SIGPIPE
signal if it tries to write to a socket whose peer has been closed; instead, the
write() fails with the error EPIPE.
z Call getaddrinfo() r to obtain a set of socket address structures for a TCP socket
that uses the port number PORT_NUM. (Instead of using a hard-coded port number,
we would more typically use a service name.) We specify the AI_PASSIVE flag e so
that the resulting socket will be bound to the wildcard address (Section 58.5). As
a result, if the server is run on a multihomed host, it can accept connection
requests sent to any of the host’s network addresses.
z Enter a loop that iterates through the socket address structures returned by the
previous step t. The loop terminates when the program finds an address struc-
ture that can be used to successfully create and bind a socket u.
z Set the SO_REUSEADDR option for the socket created in the previous step y. We
defer discussion of this option until Section 61.10, where we note that a TCP
server should usually set this option on its listening socket.
z Mark the socket as a listening socket i.
z Commence an infinite for loop o that services clients iteratively (Chapter 60).
Each client’s request is serviced before the next client’s request is accepted. For
each client, the server performs the following steps:


  • Accept a new connection a. The server passes non-NULL pointers for the
    second and third arguments to accept(), in order to obtain the address of
    the client. The server displays the client’s address (IP address plus port
    number) on standard output s.

  • Read the client’s message d, which consists of a newline-terminated string
    specifying how many sequence numbers the client wants. The server con-
    verts this string to an integer and stores it in the variable reqLen f.

  • Send the current value of the sequence number (seqNum) back to the cli-
    ent, encoding it as a newline-terminated string g. The client can assume
    that it has been allocated all of the sequence numbers in the range seqNum
    to (seqNum + reqLen – 1).

  • Update the value of the server’s sequence number by adding reqLen to
    seqNum h.


Listing 59-5: Header file used by is_seqnum_sv.c and is_seqnum_cl.c
–––––––––––––––––––––––––––––––––––––––––––––––––––––– sockets/is_seqnum.h
#include <netinet/in.h>
#include <sys/socket.h>
#include <signal.h>
#include "read_line.h" /* Declaration of readLine() */
#include "tlpi_hdr.h"

#define PORT_NUM "50000" /* Port number for server */

#define INT_LEN 30 /* Size of string able to hold largest
integer (including terminating '\n') */
–––––––––––––––––––––––––––––––––––––––––––––––––––––– sockets/is_seqnum.h
Free download pdf