Dynamic selection for network service ports?

Chris Angelico rosuav at gmail.com
Tue Apr 30 14:50:05 EDT 2019


On Wed, May 1, 2019 at 4:37 AM Markus Elfring <Markus.Elfring at web.de> wrote:
>
> > In Python, there's a certain amount of support. You can attempt to
> > bind to a port, and if you fail, try the next one in a sequence.
>
> * The zero seems to be also an usable parameter here.
>   Is the system configuration documentation unclear about the applied
>   value range for the port allocation?
>   Can it happen that special permissions would be needed for a setting?

You'll get anything in the ephemeral ports range. Your OS may control
exactly which ports are available, but at very least, the range will
include 49152-65535. Most likely it'll be wider than that. No, you
don't need any special permissions; privileged ports are all in the
0-1023 range.

> > It's simple, it's straight-forward, and it doesn't cause problems.
>
> Would you like to reduce connection management difficulties because of
> an error message like “OSError: [Errno 98] Address already in use”?

Ah. There are two causes of this. One is that you actually DO have two
programs trying to use the same port, in which case all you can do is
move the problem to the client (which of the two do you want to
connect to?). But the other cause is that you recently shut the server
down, and the port is still in the TIME_WAIT state. You can avoid this
with the SO_REUSEADDR flag. (There are potential consequences to this,
but if you're working on a LAN (or on localhost), you're almost
certainly fine.) Check the Python socket module for how to set that
flag, and see if that eliminates your hassles.

ChrisA



More information about the Python-list mailing list