TCP servers in Python - two processes want to use same port

Pif Paf p1fp4f at hotmail.com
Mon Feb 23 11:00:50 EST 2004


I am writing programs that will run as TCP servers. Briefly, I want to 
set up a TCP server on a port in such a way that if another server is 
already sitting on that port (both servers are Python programs I will be 
writing), the old one is booted off (and its process ended).

My master process is a test harness, which tests a script which as part 
of its functionality sends http GET messages. My test harness sets up 
an http server as a child process, by creating an instance of 
popen2.Popen3().

The child process is a very simple program using SimpleHTTPServer. The 
problem is when I run my test harness, break it with Ctrl-C then try to
run it again. The http server complains that it cannot bind to the socket,
as the address is already in use.

My production system will use several http servers (I'm using http GET
messages as a simple form of inter-process communication), and I don't 
want to have a situation where a program runs one time (because it's 
asking to bind to a port that isn't already in use), but the next time, 
it doesn't run because the port is being used.

Now of course I could use files to describe what ports are currently in
use and what process ids are using them, and kill the process before
trying to re-use the port, but that solution strikes me as inelegant.
Is there a better way? For example, is there a way of writing a program
that will force binding to a port, and if an existing process has that
port will kick it off (and possibly destroy it)?

--
Pif Paf



More information about the Python-list mailing list