Command Line Breakdown - Ports in Use on Ubuntu Server

Command Line Breakdown - Ports in Use on Ubuntu Server

There are plenty of material out in the web-o-sphere to determine what is using which network port.

I thought I'd take a command I recently used and break it down in order to help newer Linux Admins/Users understand the command and structure.

I used: sudo lsof -i -P -n | grep LISTEN

We'll break this down but first the output looks like this:

sshd     3420     root    3u  IPv4  15383      0t0  TCP *:22 (LISTEN)
sshd     3420     root    4u  IPv6  15392      0t0  TCP *:22 (LISTEN)
node     3456    user01  16u  IPv4  15723      0t0  TCP (LISTEN)
nginx   19676     root    7u  IPv4 323846      0t0  TCP *:80 (LISTEN)
nginx   19676     root    8u  IPv6 323847      0t0  TCP *:80 (LISTEN)

I wanted to know which ports were bound on this server. In the example output above, I can see that 22, 2368 and 80 are all being used as a listening port -- it's waiting for an inbound network connection.

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

The sudo command which you've probably used before is "super user do"; it takes the user you are logged in as and elevates you to "root" type user permissions for a short amount of time.

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

lsof is the program we are running which simply returns a list of open files.

Linux treats network connections, as well as others, as open files.

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

The -i -P -n are the flags we are passing to lsof; this is probably familiar to you from other CLI work. Linux programs tend to have two types of flags: - and --. In our case, the flags used break down as:

  • -i: Requests a list of IP sockets.
  • -P: Don't resolve the port names, instead list the port number. Note the capital "P"; some programs in Linux use case sensitive flags which mean different things.
  • -n: Don't resolve the DNS (I.E. Domain). In my case,

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

The pipe (|) warrants a section of it's own as you'll find in various Linux commands and such. I feel it's important to understand at a high-level.

It takes the output of the left operation (lsof -i ...) and gives it to the program on the right -- in this case grep which allows us to use grep as a filter which in itself is common but not the only purpose.

The output of lsof is never actually seen; instead, it's given to grep because of the | and we only see the output of that.

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

The grep is a regular expression tool which searches input for the given pattern effectively altering the output. In this case, the pattern is simply LISTEN. The output is given on the console.