3.3. Programming Assignment 1 – Simple Application Layer Protocol

You are to write a Python network server program that will accept an unlimited number of connections, one at a time [1]. Upon receiving a connection, it should send back to the client the client’s IP address. Then it should wait for commands from the client. Valid commands are “TIME”, “IP” and “EXIT”. To the TIME command, the server should return the current time (see Example of obtaining a time string). To the IP command, it should again return the client’s IP address. If the client closes the connection or does not respond with a command in a reasonable time (10 seconds), the server should close the current connection and wait for another connection (see Setting a timeout on a socket). To the EXIT command, your server should close all open sockets and exit [2].

Below are two client programs for purposes of testing your server. Feel free to modify the client programs as needed while testing your server.

3.3.1. Example of obtaining a time string

Here is an interactive Python session showing how to come up with a string containing the current time of day using the time.ctime() method from the time module.

>>> import time
>>> now = time.ctime()
>>> now
'Sun Jun  7 17:11:41 2009'

3.3.2. Setting a timeout on a socket

This example shows how to set a timeout on a socket used to accept incoming connections and how to detect a timeout events as an exception.

import socket

ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ss.bind(('', 4000))
while True:
    print "waiting for connection"
    new,addr = ss.accept()
    msg = 'init'
    while len(msg):
            msg = new.recv(30)
        except socket.timeout:
            print "got timeout"
        print msg


[1]In the last topic covered in the class, we will write a real server that can accept multiple connections at the same time. This server is a toy server, used only to experiment with using commands to construct our own application layer protocol.
[2]Protocols would normally never include a client generated command that causes the server to exit. In this case, the EXIT command is a convinence to make it easier to stop the server.