Dynamic selection for network service ports?

Chris Angelico rosuav at gmail.com
Tue Apr 30 14:03:12 EDT 2019


On Wed, May 1, 2019 at 3:51 AM Markus Elfring <Markus.Elfring at web.de> wrote:
>
> > * Which challenges from inter-process communication should be taken better into
> >   account for the involved programming interfaces (because of multi-threading)?
>
> I would like to clarify another recurring challenge with network configuration.
> A port number should be selected somehow for the service where the desired
> input data will be received.
>
> It can be nice when a fixed port can be specified for such data exchange.
> Advanced service management can achieve a reasonably safe number allocation.
>
> But I would occasionally prefer a dynamic selection for some data processing
> approaches on my test systems.
> How does the support look like for the handling of ephemeral ports by
> programming interfaces for Python?
>

Ultimately, port numbers are a communication and addressing problem.
There are two common approaches: either you use a well-known port
(such as 80 or 443 for HTTP, 53 for DNS; or similarly 5432 for
PostgreSQL), or you notify the client somehow of what port you're
using (as with FTP's "PORT" and "PASV" commands). Sometimes you can
use a hybrid, eg with some sort of connection coordinator that listens
on a well-known port, and then you say "hey, coordinator, I'm on this
IP with this port", and anyone who needs to connect to you will use
that. It's possible to use DNS for that, and many peer-to-peer systems
and multiplayer games will do this kind of thing with a central
server.

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.
(Can't get 27015? Try 27016, or 27017, or 27018, etc.) Or you can
listen without binding, and then query the socket for its port number:

>>> s = socket.socket()
>>> s.listen()
>>> s.getsockname()
('0.0.0.0', 53855)

But it's completely up to you to communicate this port assignment to
your client.

Personally, I would recommend using the well-known-port model if you
possibly can, even if it's not technically in the "Well-Known Ports"
range, like PostgreSQL's; and even if it's private use between your
client and server. Just pick a port number and run with it, and then
make it possible to override it at run-time with a command-line
argument, environment variable, or similar. It's simple, it's
straight-forward, and it doesn't cause problems.

ChrisA


More information about the Python-list mailing list