detecting socket in use on localhost

Berends j at jochem.{N0SP4M}.tv
Mon Oct 4 04:20:16 EDT 2004


Alex Martelli wrote:
> 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...?
> 
correct. 1 agent listens on a _single_ port. agents of the same sort can 
listen to a single port within a range of ports where similar / other 
agents can be active aswell. In my case say 16000-16029.

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

 > [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.
> 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.
> 
Check indeed. These two approaches will be explored, starting with the 
try, except pattern. It will be a unprivileged port (16000 up) so 
privileges wont be a problem.

I found another solution and that is parse the netstat information on 
the host and grep the range of ports and see if something is returned.

In any case thanks for your reply, feedback will be given.

Jochem



More information about the Python-list mailing list