check for unused ports and then grab one
peter at engcorp.com
Mon Sep 13 23:58:01 CEST 2004
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? Something like this is what I'm thinking:
> port = socket.getunusedport()
> Any ideas?
As Erik says, use a loop until you get a free one, catching the
exceptions that are raised as you try to use the occupied ones.
I'm curious what you are trying to do though. Normally a server
has to listen on a predefined port or the clients won't be able
to connect, and a client doesn't need to specify which port it
will bind to as the OS will pick a free one automatically. I've
never had to do what you are trying to do, thus my curiosity...
More information about the Python-list