Skip to main content

Need a random TCP port number for your Internet server application?

When writing a TCP server, the most difficult task at the beginning of the process is deciding what port number to use. The Transmission Control Protocol has a range of port numbers from 0 to 65535. The range of an unsigned short integer (2 bytes). In today's terms, that is a fairly small space of numbers and it is quite crowded out there. Fortunately, there are some rules you can follow:

  • Specifying port 0 will result in a random port being assigned by the OS. This is ideal only if you have some sort of auto-discovery mechanism for finding the port your users are interested in (e.g. connecting to a web server on port 80 and requesting the correct port number). Otherwise, you'll have to occupy an "open" port number.
  • The first 1023 port numbers are reserved by some operating systems (e.g. Linux). Under those OSes, special permissions are required to run services on port numbers under 1024. Specifically, the process either has to have been started by the 'root' user OR been declared okay by the 'root' user with special kernel commands (e.g. setcap 'cap_net_bind_service=+ep' /path/to/program).
  • Of the remaining port numbers, huge swaths of the space have been used for what are known as Ephemeral Ports. These are randomly selected and used for temporary connections. 1024-5000 have been used by a number of OSes. IANA officially recommends 49152-65535 for the Ephemeral Ports.
  • Port 8080 is the most common "high" port that people use (i.e. alternate web server port). Avoiding that is a good idea.
Having all of that knowledge is useful but what you need is a random number generator that can generate that port number for you. Without further ado, your new port number awaits your clickity click or tappity tap:

Get a random TCP port number

As long as it doesn't output 8080, you are good. If it does output 8080 and/or stomping on IANA assignments bothers you, reload the page and try again.