choosing random dynamic port number

Giampaolo Rodola' gnewsg at gmail.com
Fri Jan 4 12:25:28 CET 2008


On 3 Gen, 23:21, Fredrik Lundh <fred... at pythonware.com> wrote:
> Emin.shopper Martinian.shopper wrote:
> > Is there a good way to choose/assign random dynamic port numbers in python?
>
> > I had in mind something like the following, but if multiple programs are
> > generating random port numbers, is there a way to check if a given port
> > number is already taken?
>
> >     def GenerateDynamicPortNumber():
> >         "Generate a random dynamic port number and return it."
> >         # port numbers between 49152 to 65535 are dynamic port numbers
> >         return 49152 + random.randrange(15000)
>
>     def GenerateDynamicPortNumber():
>         return 0
>
> (to get the actual number, use getsockname() on the socket after you've
> called "bind" on it)
>
> </F>

By using 0 as port number value you let kernel choose a free
unprivileged random port:

 >>> import socket
 >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 >>> s.bind(('', 0))
 >>> s.getsockname()
 ('0.0.0.0', 3070)



More information about the Python-list mailing list