check for unused ports and then grab one

Andrew Dalke adalke at
Tue Sep 14 04:21:43 CEST 2004

Peter Hansen wrote:
> I'm curious what you are trying to do though.  Normally a server
> has to listen on a predefined port or the clients won't be able
> to connect, and a client doesn't need to specify which port it
> will bind to as the OS will pick a free one automatically.  I've
> never had to do what you are trying to do, thus my curiosity...

I needed something like this once.  I wanted to write
an interface to an external program.  It didn't take
stdin/stdout/files for input.  Instead, it acted as a
server and I needed to make a network connection to it.

It took a port number on the command line so I first
scanned a range to ensure a port was available then
passed that port number to the exec'd client.

Yes, there's a race condition, but at most I expected
two or three processes running on the system, all
from friendly users.  AFAICT there never was a problem.

Since then the vendor changed the code to support
connections via stdin/stdout.

				dalke at
   And the port 0 trick is new to me too.

More information about the Python-list mailing list