Sockets: Internet Domains 1223
h seqNum += reqLen; / Update sequence number /
if (close(cfd) == -1) /* Close connection */
errMsg("close");
}
}
––––––––––––––––––––––––––––––––––––––––––––––––––––sockets/is_seqnum_sv.c
Client program
The client program is shown in Listing 59-7. This program accepts two arguments. The
first argument, which is the name of the host on which the server is running, is
mandatory. The optional second argument is the length of the sequence desired by
the client. The default length is 1. The client performs the following steps:
z Call getaddrinfo() to obtain a set of socket address structures suitable for con-
necting to a TCP server bound to the specified host q. For the port number,
the client specifies PORT_NUM.
z Enter a loop w that iterates through the socket address structures returned by the
previous step, until the client finds one that can be used to successfully create e
and connect r a socket to the server. Since the client has not bound its socket,
the connect() call causes the kernel to assign an ephemeral port to the socket.
z Send an integer specifying the length of the client’s desired sequence t. This
integer is sent as a newline-terminated string.
z Read the sequence number sent back by the server (which is likewise a newline-
terminated string) y and print it on standard output u.
When we run the server and the client on the same host, we see the following:
$ ./is_seqnum_sv &
[1] 4075
$ ./is_seqnum_cl localhost Client 1: requests 1 sequence number
Connection from (localhost, 33273) Server displays client address + port
Sequence number: 0 Client displays returned sequence number
$ ./is_seqnum_cl localhost 10 Client 2: requests 10 sequence numbers
Connection from (localhost, 33274)
Sequence number: 1
$ ./is_seqnum_cl localhost Client 3: requests 1 sequence number
Connection from (localhost, 33275)
Sequence number: 11
Next, we demonstrate the use of telnet for debugging this application:
$ telnet localhost 50000 Our server uses this port number
Empty line printed by telnet
Trying 127.0..0.1...
Connection from (localhost, 33276)
Connected to localhost.
Escape character is '^]'.
1 Enter length of requested sequence
12 telnet displays sequence number and
Connection closed by foreign host. detects that server closed connection