Lsof Check Listening Ports
Luke Hebert
- 2 minutes read - 298 wordsWhen you need to know which ports a host is actually listening on, lsof paired with a quick filter gets you the answer in one line. No need to dig through ss or netstat output and mentally sort through TIME_WAIT or ESTABLISHED connections.
The Command
lsof -i -n | egrep 'COMMAND|LISTEN'Breaking it down:
lsof -ilists all open files that are network sockets.-nskips DNS resolution, so you get raw IP addresses and port numbers instead of hostnames. This also makes the output faster.egrep 'COMMAND|LISTEN'keeps only the header line and lines where the state isLISTEN, filtering out established connections, time-wait sockets, and everything else.
Example Output
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 1234 root 6u IPv4 12345 0t0 TCP *:80 (LISTEN)
nginx 1234 root 7u IPv4 12346 0t0 TCP *:443 (LISTEN)
mysqld 5678 mysql 22u IPv4 12347 0t0 TCP *:3306 (LISTEN)Useful Variations
Filter to a specific port:
lsof -i -n -P | egrep 'COMMAND|:8080'Show only IPv4 listeners:
lsof -i4 -n | egrep 'COMMAND|LISTEN'Show only IPv6 listeners:
lsof -i6 -n | egrep 'COMMAND|LISTEN'When to Use This
- You suspect a service is bound to the wrong interface or port.
- You are auditing a host before opening a firewall rule and want to confirm what is actually exposed.
- A port conflict is preventing a service from starting, and you need to identify the offending process.
Note
lsof requires root (or sudo) to see sockets owned by other users. Without elevated privileges you will only see listeners belonging to the current user.
Alternatives
If lsof is not available on the system, ss is a lighter-weight option:
ss -tlnpThis shows TCP listeners with the owning process name and PID in a single pass.