Better than netstat: lsof tells us who is listening to what

This post was written by eli on December 1, 2018
Posted Under: Internet,Linux

Be sure to read the first comment below, where I’m told netstat can actually do the job.

OK, so we have netstat to tell us which ports are opened for listening:

$ netstat -n -a | grep "LISTEN "

Thanks, that nice, but what process is listening to these ports? For TCP sockets, it’s (as root):

# lsof -n -P -i tcp 2>/dev/null | grep LISTEN

The -P flag disables conversion from port numbers to protocol names. -n prevents conversion of host names.

Reader Comments

Hi Elli,

>OK, so we have netstat to tell us which ports are >opened for listening:

>$ netstat -n -a | grep “LISTEN ”

>Thanks, that nice, but what process is listening to >these ports?

Actually you can get the process also with netstat using the -p flag

For example,

netstat -n -ap | grep “LISTEN ”

tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 830/sshd
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 831/cupsd
tcp6 0 0 127.0.0.1:36391 :::* LISTEN 4064/java
tcp6 0 0 :::22 :::* LISTEN 830/sshd
tcp6 0 0 ::1:631 :::* LISTEN 831/cupsd

See man netstat:


-p, –program
Show the PID and name of the program to which each socket belongs.

Regards,
Rami Rosen

#1 
Written By Rami Rosen on January 31st, 2019 @ 11:01

Thanks, that’s really cute. I’d consider changing the title of this post, but nah.

I’ll just add that you need to be root to see the listening processes that don’t belong to yourself, even with netstat -ap.

#2 
Written By eli on January 31st, 2019 @ 11:07

Add a Comment

required, use real name
required, will not be published
optional, your blog address