how to get any available port

Steve Holden steve at holdenweb.com
Wed Oct 5 09:58:50 CEST 2005


jepler at unpythonic.net wrote:
> Apparently, calling bind() with a zero "port" will choose some available port
> number, as demonstrated by this program:
> 
> import socket
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.bind(("", 0))
> print s.getsockname()
> 
> Here's how it behaved over several runs:
> $ python soc.py 
> ('0.0.0.0', 34205)
> $ python soc.py 
> ('0.0.0.0', 34206)
> $ python soc.py 
> ('0.0.0.0', 34207)
> 
> I don't know for sure whether this is standard behavior for sockets, or whether
> it's a special behavior of linux.
> 
It's been standard behaviour ever since the Berkeley socket interface 
was defined, as far as I know.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list