check for unused ports and then grab one

Michael Fuhr mfuhr at fuhr.org
Tue Sep 14 15:59:13 CEST 2004


Brad Tilley <bradtilley at usa.net> writes:

> > def listen(server_param, port_param):
> >    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> >    s.bind((server_param, port_param))
> >    s.listen(1)
> >    ipaddr, port = s.getsockname()
> >    print ipaddr, port

[snip]

> Not that it matters, but this code always gets a much higher port number 
> on my Linux computers:

Different systems have different ephemeral port ranges; they can
often be configured.  Here are some examples:

Linux
$ sysctl net.ipv4.ip_local_port_range
net.ipv4.ip_local_port_range = 32768    61000

FreeBSD
$ sysctl net.inet.ip.portrange
net.inet.ip.portrange.lowfirst: 1023
net.inet.ip.portrange.lowlast: 600
net.inet.ip.portrange.first: 1024
net.inet.ip.portrange.last: 5000
net.inet.ip.portrange.hifirst: 49152
net.inet.ip.portrange.hilast: 65535
net.inet.ip.portrange.randomized: 1

Solaris 
$ ndd /dev/tcp tcp_smallest_anon_port
32768
$ ndd /dev/tcp tcp_largest_anon_port
65535

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



More information about the Python-list mailing list