check for unused ports and then grab one
mfuhr at fuhr.org
Tue Sep 14 00:14:27 CEST 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)
ipaddr, port = sock.getsockname()
print 'listening on %s port %d' % (ipaddr, port)
More information about the Python-list