Reserve Ephemeral ports

my apps use port 40001; however, for example, firstly, I ftp to other server, it made a high port locally, remote is port 21, unfortunately, it hit my port 40001 and my apps is unable to startup. This chance is very very little, but I hit it. Can resevse my port 40001? otherwise command don't use it

You could put a tcp_relay.c listener on 40001 to forward the connection to localhost:21. It can pick up the port (bind) for listen() even if in use for non-bound sockets, with SO_REUSEADDR.

Add your application and port to the /etc/services file. It will prevent any other program to use the port (Obviously, any other program that is well written :P)

myapp      40001/tcp
myapp      40001/udp

I don't think that's true, even by convention. How could even a well-written program prevent itself from being randomly assigned a high port number? It has no choice in the matter, and the kernel certainly doesn't check /etc/services...

This may differ from system to system, but I think you're safe from random assignments when you use numbers less than 32768.

Hi Corona688,

I was under the impression that the kernel would not use ports listed on /etc/services for new connections.

goobid,

One solution could be change the value of the local port range in order to prevent the kernel to assign any random port below 40001. For example on Linux you can change it as follows:

sysctl -w "net.ipv4.ip_local_port_range=40002  65000"

# Add the line to /etc/sysctl.conf file a well
echo "net.ipv4.ip_local_port_range = 40002  65500" >>/etc/sysctl.conf

Under normal circumstances 25,000 ports for random assignments should be enough.

Here is a nice reference to change the value of the 'ephemeral' ports in other OSes.
The Ephemeral Port Range

The kernel almost never reaches into userspace of its own volition. "Almost" because it has to when it boots, just once, to run /sbin/init.

I don't think that's necessary if he could just use a port less than 32768 in the first place. A solution that doesn't require root access to every computer you want to run it on is nice. That setting also proves that Linux doesn't assign random ports below 32768 by default:

$ cat /proc/sys/net/ipv4/ip_local_port_range 
32768   61000