Chapter 12: Networks
printf("\nBytes received: %u\n", bytes);
printf("Text: ’%s’\n", buf);
/* End communication (i.e. close socket) */
close(sockfd);
}
The Internet superdaemon (inetd,xinetd, or similar) normally uses a built-in echo server. Consequently,
the source code can be tested immediately after compilation.
wolfgang@meitner>./echo_client
Connect to 192.168.1.20
Numeric: 335653056
Send: ’Hello World’
Bytes received: 11
Text: ’Hello World’
The following steps are performed by the client:
- An instance of thesockaddr_instructure is generated to define the address of the server to
be contacted.AF_INETindicates that it is an Internet address and the target server is precisely
defined by its IP address (192.168.1.20) and port number ( 7 ).
Also, the data from the host are converted to the network byte order.htonsis used for the
port number, and theinet_addrauxiliary function performs the conversion implicitly by
translating the text string with a dotted decimal address into a number. - A socket is created in the kernel by means of thesocketfunction, which (as shown below)
is based on thesocketcallsystem call of the kernel. The result returned is an integer num-
ber that is interpreted as a file descriptor — and can therefore be processed by all functions
available for regular files, as described in Chapter 8. In addition to these operations, there
are other network-specific ways of handling the file descriptor; these permit exact setting of
various transmission parameters not discussed here. - A connection is set up by invoking theconnectfunction in conjunction with the file descrip-
tor and theservervariable that stores the server connection data (this function is also based
on thesocketcallsystem call). - Actual communication is initiated by sending a text string (‘‘Hello World‘‘ — how could it
be anything else?) to the server by means ofwrite. Writing data to a socket file descriptor
is the equivalent of sending data. This step is totally independent of the server location and
the protocol used to set up the connection. The network implementation ensures that the
character string reaches its destination — no matter how this is done. - The server response is read byread, but a buffer must first be allocated to hold the data
received. As a precaution, 1,000 bytes are reserved in memory, although we only expect the
original string to be returned.readblocks until the server supplies a response, and it then
returns the number of bytes received as an integer number.
Because strings in C are always null-terminated, 11 bytes are received, although the mes-
sage itself appears to be only 10 bytes long.