detecting socket in use on localhost

Bryan Olson fakeaddress at
Tue Oct 5 06:28:01 CEST 2004

Berends wrote:

 > Alex Martelli wrote:
 >> Berends 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...?
 > correct.
 >> [1] try connecting to
 >> that port and see if that succeeds (then there must be some listener) or
 >> fails (then, probably no listener);
 >> [2] try binding to that port and see if
 >> that succeeds (then, no listener) or fails because nobody's listening.

And Berends had a method [3], which is to ask the system.

A few notes:

Method [1] is one way to do a "port scan".  Both network
attackers and defenders regularly do port-scans.  Google the
term for further info.

"On the localhost" is open to misinterpretation.  The name
'localhost' typically resolves to the loop-back adapter, with
the IPV4 address, and is accessible only from the
localhost.  Each adapter has its own IP address, with its own
set of TCP ports and UDP ports.  Any host with Internet
connectivity should have at least two adapters and addresses:
the loop-back adapter and an external network interface.

Servers most often bind to INADDR_ANY, which is represented by
the reserved (IPV4) address, and means the server should
listen on *all* the host's adapters.  A request to bind to
(INADDR_ANY, myport) will fail if myport is already bound on any
of the host's adapters.

 >> 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.

"Most situations" is hard to define.  I know of two common
situations that call for methods like [1]: Server operators
often want to verify their service is running, and often want to
check that common-but-unneeded services are *not* running. The
former calls for a "heartbeat", and the later for a port-scan.


More information about the Python-list mailing list