Why are the first 1024 ports restricted to the root user only?
Binding is an integral step for server side socket. It’s like providing some address to end-user (server). So, we assign an IP address and a port number for running a server. But we can not provide any random port number to a server. The port numbers from 1 to 1023 are restricted for root user only and we can not assign those ports without having root access.
The reason behind this restriction is that most major network services like HTTP, FTP, SSH, Telnet, POP etc. runs in this range. So, if any one is allowed to run on those port, following circumstances may arise :
- An untrusted user could run a program that listened on these ports for login (access) details.
- An untrusted user could run an unauthorized server application.
Below program verifies the fact that port numbers from 1 to 1023 are restricted for root access.
We use bind() function which returns 0 on success and -1 on failure. We call bind in a loop for different port numbers until it returns 0.
Server Created Binded Correctly on port number 1024
How to allow non root access to bind below port number 1024?
But there are two method by which we can assign port number less than 1024 without having root privilege :
- Method 1 : Using CAP_NET_BIND_SERVICE to grant low-numbered port access to a process :
For this, we just need to run following command in terminal :
sudo setcap CAP_NET_BIND_SERVICE=+eip /path/to/binary
- Method 2 : Using authbind to grant one-time access, with finer user/group/port control. Let we have to assign port number 80. For this, following steps required :
- Install authbind using any package manager
- Run following two commands one by one in terminal :
sudo touch /etc/authbind/byport/80 sudo chmod 777 /etc/authbind/byport/80
Here, 80 is given in end of command as we are attempting to assign port number 80.
- Now execute following command in terminal
authbind --deep /path/to/binary command line args
This article is contributed by Aditya Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.