How can I check which ports are busy and which ports are free on my Linux machine?

The command

netstat -antu

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 localhost or 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. sudo).

Usage: option -l for listening ports, option -n to bypass DNS resolution, and the filter on source port NN: src :NN (replace NN by the port you want to monitor). For more options, see man ss

ss -ln src :NN

Examples:

[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)