Check Open Ports in Linux: ss, netstat, lsof
Part of network diagnostics, is checking services with open ports on Linux.
How to Check Open Ports on Linux
To check open ports with the netstat, the "-tunl" options can be used:
- -t for TCP
- -u for UDP
- -n to not resolve names
- -l for open ports (listen)
In this example, netstat lists the open TCP/UDP ports:
$ netstat -tunlActive Internet connections (only servers)Proto Local Address Foreign Addresstcp 127.0.0.53:53 0.0.0.0:* tcp 0.0.0.0:22 0.0.0.0:*tcp6 0 :::22 :::* udp 127.0.0.53:53 0.0.0.0:*
Netstat with the -p option shows the processes owning the ports. To use this option you need to be root:
$ sudo netstat -tunlpActive Internet connections (only servers)Proto Local Address State PID/Program name tcp 127.0.0.53:53 LISTEN 24813/systemd-resol tcp 0.0.0.0:22 LISTEN 9857/sshd tcp6 :::22 LISTEN 9857/sshd udp 127.0.0.53:53 24813/systemd-resol
The ss command can also show open ports with the same option:
# ss -tunelpNetid Local Address:Port Peer Address:Port udp 127.0.0.53%lo:53 0.0.0.0:* ("systemd-resolve",pid=355)udp 0.0.0.0:68 0.0.0.0:* ("dhclient",pid=17984)udp 0.0.0.0:5353 0.0.0.0:* ("avahi-daemon",pid=27533)tcp 0.0.0.0:22 0.0.0.0:* ("sshd",pid=14825)
The lsof Command on Linux
Since everything in Linux is a file, network connections can also be viewed as an "open file". The "lsof" command can be used in this context to see the files that correspond to Internet addresses.
The "-i" option of lsof filters open files of the Internet address type. It is necessary to run lsof as root:
$ sudo lsof -i
COMMAND PID USER FD TYPE NODE NAME
sshd 9857 root 3u IPv4 TCP *:ssh (LISTEN)
sshd 9857 root 4u IPv6 TCP *:ssh (LISTEN)
systemd-r 24813 systemd-resolve 12u IPv4 UDP localhost:domain
systemd-r 24813 systemd-resolve 13u IPv4 TCP localhost:domain (LISTEN)
The fuser Command on Linux
The "fuser" command can also be used to show information about a specific open port. It identifies processes through files or sockets, returning the PID of the processes:
$ sudo fuser 22/tcp22/tcp: 9857 24313 24400
To know which process is using a specific file:
$ fuser -v /bin/bash USER PID ACCESS COMMAND/usr/bin/bash: ec2-user 16092 ...e. bash
The commands netstat, ss, lsof, and fuser are used to view open ports on the local machine.
There is a tool called nmap that can also discover open ports on both the local machine and remote machines.
Practice your knowledge with our quiz
These questions cover key concepts discussed in the article about open ports on Linux, providing an opportunity for readers to test their knowledge after reading the material.
[streamquiz id="64"]Learn much more about Linux in our online course. You can enroll here. If you already have an account, or want to create one, just log in or create your user here.
Did you like it? Share
That was just one piece. The course teaches the whole path — from your first command to exam day.