check for unused ports and then grab one

Michael Fuhr mfuhr at fuhr.org
Mon Sep 13 18:14:27 EDT 2004


Erik Heneryd <erik at heneryd.com> writes:

> Brad Tilley wrote:
> > Instead of me arbitrarily assigning a high port number to a variable, is 
> > it possible to check for ports that are unused and then randomly assign 
> > one of them to a variable?
>
> No.  Trial and error until you find one.

On many systems, binding to port 0 will give you an available port;
you can then use getsockname() to find out which port you got.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.bind(('', 0))
sock.listen(socket.SOMAXCONN)
ipaddr, port = sock.getsockname()
print 'listening on %s port %d' % (ipaddr, port)

-- 
Michael Fuhr
http://www.fuhr.org/~mfuhr/



More information about the Python-list mailing list