Is there any command line command or any other way to find and list out the busy and free port numbers on my Linux machine?
will show all tcp and udp ports in use. The output will look something like this:
Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:59753 0.0.0.0:* LISTEN
The number after the colon in the Local Address field shows the port in use. If the state is "LISTEN" it means a port that is using for incoming connections. If the IP address in the
Local Address field is
0.0.0.0 it means incoming connections will be accepted on any IP address assigned to an interface - so this means from connections originating outside of your machine.
If it said
127.0.0.1 it would be only accepting connections from your machine.
Additionally, if you add the
-p parameter, and run it as root, it will show the process that opened the port:
$ sudo netstat -antup Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:59753 0.0.0.0:* LISTEN 860/rpc.statd
Anything not shown as being in use is free, however users (unprivileged accounts) can only open ports above 1023.
I compiled a small list myself.
Some of my favorites are:
netstat -tulpn lsof -i -n -P
A good and reliable way to check for ports opened is using
ss (replacement for the deprecated
netstat), it's usable in a script without requiring elevated privileges (i.e.
-l for listening ports, option
-n to bypass DNS resolution, and the filter on source port
src :NN (replace
NN by the port you want to monitor). For more options, see
ss -ln src :NN
[user@server ~]# ss -ln src :80 State Recv-Q Send-Q Local Address:Port Peer Address:Port LISTEN 0 128 *:80 *:* [user@server ~]# ss -ln src :81 State Recv-Q Send-Q Local Address:Port Peer Address:Port
And in a script, using grep, we can test if the output contains the port we requested. Example with port 80 in use (see above):
myport=80 # count the number of occurrences of port $myport in output: 1= in use; 0 = not in use result=$(ss -ln src :$myport | grep -Ec -e "\<$myport\>") if [ "$result" -eq 1 ]; then echo "Port $myport is in use (result == $result) " else echo "Port $myport is NOT in use (result == $result) " fi # output: Port 80 is in use (result == 1)
Example with port 81 not in use (see above)
myport=81 result=$(ss -ln src :$myport | grep -Ec -e "\<$myport\>") if [ "$result" -eq 1 ]; then echo "Port $myport is in use (result == $result) " else echo "Port $myport is NOT in use (result == $result) " fi # output: Port 81 is NOT in use (result == 0)
telnet localhost <PORT_NUMBER>
If the port is free you will get an error. If the port is in use telnet will connect.