How to select a static port number for a custom app? How to select a static port number for a custom app? linux linux

How to select a static port number for a custom app?


For a static application, consider checking /etc/services to find a port that will not collide with anything else you are using and isn't in common use elsewhere.

$ tail /etc/servicesnimspooler      48001/udp                       # Nimbus Spoolernimhub          48002/tcp                       # Nimbus Hubnimhub          48002/udp                       # Nimbus Hubnimgtw          48003/tcp                       # Nimbus Gatewaynimgtw          48003/udp                       # Nimbus Gatewaycom-bardac-dw   48556/tcp                       # com-bardac-dwcom-bardac-dw   48556/udp                       # com-bardac-dwiqobject        48619/tcp                       # iqobjectiqobject        48619/udp                       # iqobject


If you can't predict the exact kind of environment your application is going to run, just don't bother with this. Pick any number over 1024 and also make it configurable so the user can change it in case of conflict with another service/application.

Of course you can still avoid very common ports like 8080 (alternative HTTP) or 3128 (proxies like squid), 1666 (perforce), etc. You can check a comprehensive list of known ports here, or take a look at /etc/services.


If you don't care about the port number, and don't mind that it changes every time your program is run, simply don't bind the port before you listen on it (or bind with port 0, if you want to bind a specific IP address). In both cases, you're telling the OS to pick a free port for you.

After you begin listening, use getsockname to find out which port was picked. You can write it to a file, display on it on the screen, have a child inherit it via fork, etc.