lsof: find out what ports are being used in the background.

When working with Linux, sometimes you want to install 2 different pieces of server software. Once you’ve finished doing so, you may run into an error or 2 about it not starting up through either systemd or by running it directly. In most cases, this is usually caused by the both of them attempting to listen on the same port. You may have a hard time diagnosing what’s causing it, but thanks to lsof you won’t have to.

lsof

lsof is a program located under the /usr/bin/ folder. This particular program displays a list of processes and what they’re accessing on the system. It also displays network connections running in the background, along with the ports they’re on and whether they’re listening for incoming requests or have already been established.

Simply run the following command to get started:

sudo lsof

lsof will list everything by default, thus overwhelming your bash shell space. We are going to need something a little more condensed and easier to read. In order to do that, we are going to type in this command:

sudo lsof -i -P -n

We now have a more condensed version of lsof being displayed. -i tells it to display only connection information. -P makes sure that the actual ports are displayed so that it can be identified easier. -n forces it to display IP addresses instead of a domain/hostname, again makes it easier to identify.

In some cases, you may see 2 of the same ports running even though they’re not causing any problems. This is because each program is listening for incoming connections from both IPv4 and IPv6 addresses which is considered to be normal.

You can also condense the list down even further by running the following command:

sudo lsof -i -P -n | grep -i 'LISTEN'

Now lsof will display only programs that are actively listening for incoming connections. You may also replace LISTEN with ESTABLISHED to display active connections.