Binding port 0 to avoid port collisions

17 points by hwayne


mk12

I find it sad how little used Unix domain sockets are. Not only are they more efficient than TCP loopback, but you can name them whatever you want! And put permissions on them! It completely avoids the issue of remembering which port is for what, or picking an unused port. I try to use them wherever possible in my homelab, but lots of software doesn't support them or treats them like a weird edge case. I wish I could go back in time and advocate to (1) make them more portable (Windows, I guess), (2) raise the annoying ~100 char path limit, and (3) standardize some way of specifying them to servers like unix:///path/to/socket?mode=660.

matklad

Is there a similar trick that extends to more than one process/port? Let’s say I want to start three processes that need to talk to each other, and each process accepts ports of the peers on the CLI. Each process can listen on port zero, and learn its own port number which can be passed onto peers, but this is too late to pass it on the CLI argument.

dpc_pw

If you're already learning things in this area, I highly recommend investigating listenfd and systemfd Rust crates. They are very handy for working on network projects alongside cargo-watch, etc. Also listenfd can be used to implement systemd socket activation handover.

pie_flavor

Is this... uncommon knowledge? Random ports are used everywhere for everything. Do people just import get-port from NPM without knowing how it works?