how to get any available port

jepler at unpythonic.net jepler at unpythonic.net
Tue Oct 4 17:11:15 EDT 2005


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.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20051004/665f9a04/attachment.sig>


More information about the Python-list mailing list