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

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.


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/services
nimspooler      48001/udp                       # Nimbus Spooler
nimhub          48002/tcp                       # Nimbus Hub
nimhub          48002/udp                       # Nimbus Hub
nimgtw          48003/tcp                       # Nimbus Gateway
nimgtw          48003/udp                       # Nimbus Gateway
com-bardac-dw   48556/tcp                       # com-bardac-dw
com-bardac-dw   48556/udp                       # com-bardac-dw
iqobject        48619/tcp                       # iqobject
iqobject        48619/udp                       # iqobject

Tags:

Linux

Port