detecting socket in use on localhost

Alex Martelli aleaxit at yahoo.com
Mon Oct 4 03:47:22 EDT 2004


Berends <j at jochem.{N0SP4M}.tv> wrote:

> I am looking for some code to detect whether or not there is already a
> listener to a socket (tcp or udp) on the localhost.

Hmmm, you mean to a _port_, I guess...?

> I am writing some software that can be run multiple times on a localhost
> and each will instantiate a listener in a range of ports. I have checked
> several resources (Cookbook, Python Network Programming (Goerzen), 
> Programming Python(Lutz)) but cannot find the crux.
> 
> Anyone care to point me to some nice methods?

If you need a cross-platform solution I think you'll need to adopt a
trial-and-error strategy.  Two main possibilities: try connecting to
that port and see if that succeeds (then there must be some listener) or
fails (then, probably no listener); try binding to that port and see if
that succeeds (then, no listener) or fails because nobody's listening.
In most situations I'd go for the latter, as the former may be less
reliable and might have undesired side effects (at a minimum, footprints
in the listener's logs); however, the latter may not be feasible if the
ports you want to check are privileged ones (<=1024 or whatever) and
your process lacks the necessary privileges.


Alex



More information about the Python-list mailing list