Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 12: Networks


printf("Bytes received: %u\n", bytes);
printf("Text: ’%s’\n", buf);

/* Send response */
write(clientfd, buf, bytes);
}
}

The first section is almost the same as the client code. An instance of thesockaddr_instructure is created
to hold the Internet address of the server, but this is done for a different reason. The address of the server
to which the client wishes to connect is specified in the client code. In this case, the address specified is
that used by the server to wait for connections. The socket is generated in exactly the same way as for the
client.


In contrast to the client, the server does not actively attempt to set up a connection to another program
but simply waits passively until it receives a connection request. Three library functions (again based on
the universalsocketcallsystem call) are required to set up a passive connection:


❑ bindbinds the socket to an address (192.186.1.20:7777in our example).^6
❑ listeninstructs the socket to wait passively for an incoming connection request from a client.
The function creates a wait queue on which all processes wishing to establish a connection are
placed. The length of the queue is defined by the second parameter. (SOMAXCONNspecifies that the
maximum system-internal number must be used so as not to arbitrarily restrict the maximum
number of waiting processes.)
❑ Theacceptfunction accepts the connection requestof the first client on the wait queue. When
the queue is empty, the function blocks until a client wishing to connect is available.

Again, actual communication is performed byreadandwrite, which use the file descriptor returned by
accept.


The client connection data (supplied byacceptand consisting of the IP address and port number) are
output for information purposes. While the client IP address for a specific computer is fixed, the port
number is selected dynamically by the computer’s kernel when the connection is established.


The function of the echo server is easily imitated by reading all client input withreadand writing it back
withwritein an endless loop. When the client closes the connection,readreturns a data stream that is
0 bytes long so that the server then also terminates.


Client Server
wolfgang@meitner>./stream_client wolfgang@meitner>./stream_server
Connect to 192.168.1.20 Wait for connection on port 7777
Numeric: 335653056
Client: 192.168.1.10:3505
Send: ’Hello World’ Numeric: 3232235786
Bytes received: 11
Bytes received: 11 Text: ’Hello World’
Text: ’Hello World’
Connection closed.

(^6) Under Linux (and all otherUnixflavors), all ports between 1 and 1,024 are referred to asreserved portsand may be used only by
processes with root rights. For this reason, we use the free port number 7,777.

Free download pdf