Simple TCP/IP time server
This program demonstrates a simple TCP/IP server. It will accept a connection from a client application, and echo the current time to it.
Programming Issues
This program illustrates the classic process for a TCP/IP server program. Summarised, it is as follows:
- Create a socket with a call to
socket()
- Create and initialize a socket address strucure
with the IP address set to
INADDR_ANY
(the server will listen on any IP address) and the port to whichever one you wish to use. - Call
bind()
to bind the socket address to the socket. - Call
listen()
to indicate that this is a passive socket, that we want to accept incoming requests rather than make outgoing ones. - Enter a loop in which we:
- Call
accept()
to wait for an incoming connection - Service the request on our new connection
close()
our connection, and continue the loop to wait for a new one
- Call
Note that it's present form, the server enters an infinite loop and
has no mechanism for closing itself. We have to use a command such as
kill
to terminate it.
Usage
Once launched in the background, the server can be used either with a dedicated time client, or simply by telnetting to it. For the latter approach, the following is a sample session using Linux:
[paul@localhost paul]$ ./timeserv 3357 & [paul@localhost paul]$ telnet localhost 3357 Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Sat Oct 16 19:26:17 1999 Connection closed by foreign host. [paul@localhost paul]$
After executing telnet and receiving some initialisation output, we the server process echoing the current time to us, then closing the connection.
You can specify the port number to listen to as a command line argument. The program will default to TIME_PORT (#defined as 2002) if one is not supplied.