Using lsof To Discover What Ports Are In Use

A task that comes up often enough that you need to memorize a command and it’s options is to find out what’s listening on a port. Sometimes it’s a result of seeing an error like Address already in use or Socket in use when you try to start a new network process. Or you might need to know what’s listening on what port to configure a firewall etc.

There are other tools that will show you the open network sockets such as nestat and ss but I always find myself using lsof. The output is nicely formatted and informative.

The basic command to list network sockets is:

# lsof -i

This will print out information like the following:

# lsof -i
COMMAND  PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd     524     root    3u  IPv4  15398      0t0  TCP *:ssh (LISTEN)
nginx    632     root   10u  IPv4  15704      0t0  TCP *:https (LISTEN)
nginx    632     root   11u  IPv4  15705      0t0  TCP *:http (LISTEN)
nginx    634 www-data   10u  IPv4  15704      0t0  TCP *:https (LISTEN)
nginx    634 www-data   11u  IPv4  15705      0t0  TCP *:http (LISTEN)

These sockets have the (LISTEN) status. This means that they are open and waiting for something to connect. This line from lsof -i show’s an SSH process that is connected to a client, demonstrated by the (ESTABLISHED) status.

sshd    1779 root    3u  IPv4  19847      0t0  TCP 138.68.52.22:ssh->cpc93350-example-1.cable.virginm.net:53612 (ESTABLISHED)

This is usually enough, coupled with grep you can find the process/port that you need.

If you already know what port you’re interested in your can narrow the output by specifying the protocol and port e.g. TCP:22 for SSH:

# lsof -i TCP:22
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
sshd     524 root    3u  IPv4  15398      0t0  TCP *:ssh (LISTEN)