choosing random dynamic port number

Fredrik Lundh fredrik at
Thu Jan 3 23:21:27 CET 2008

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)


More information about the Python-list mailing list