Checking Listening Ports and Services in Use(netstat,ss,lsof)
When troubleshooting network or specific service communication issues, identifying the ports in use is essential.
This guide introduces how to check which services are using specific ports with commands like netstat
, ss
, and lsof
.
netstat
netstat
provides a wide range of communication-related information, including port usage and socket states. Here's how to use it:
sudo netstat -tunlp
Options used:
-
-t
- Shows TCP communication ports. -
-u
- Shows UDP communication ports. -
-n
- Displays hosts, services, and users in numeric format (IP, port, UID) -
-l
- Lists only listening ports. -
-p
- Displays PID and program name.
output:
To filter results using grep, for example, to find the service using TCP port 22:
sudo netstat -tnlp | grep :22
The output will show that port 22 is being used by SSH.
If no output is shown, it means no service is using that port with the specified protocol
Although newer tools like ss and ip commands are gradually replacing netstat, it is still widely supported and frequently used.
ss
ss
is a tool for querying socket information and is intended as a replacement for netstat.
It is faster and provides a cleaner output format. The command options are similar to those of netstat:
sudo ss -tunlp
The output format is similar to netstat but with slight differences in presentation.
lsof
lsof
is a powerful tool that provides detailed information about files opened by processes.
Since sockets are treated as files in Unix-based systems, lsof can also be used to check listening ports.
To check listening ports:
sudo lsof -nP -iTCP -sTCP:LISTEN
Options used:
-n
- Displays IP addresses instead of hostnames.-p
- Displays port numbers instead of service names.-iTCP -sTCP:LISTEN
- Filters for TCP protocol and sockets in the LISTEN state.
To check a specific port:
sudo lsof -nP -iTCP:3306 -sTCP:LISTEN
For instance, the output will show that MySQL is using port 3306 in this case.
This guide explained how to check listening ports and identify processes (services) using specific ports with the netstat
, ss
, and lsof
commands.