5

Using lsof, I can find all of the processes with a TCP socket listening for connections:

lsof -Pni -sTCP:LISTEN

e.g.:

COMMAND   PID   USER  FD  TYPE  DEVICE SIZE/OFF NODE NAME
cupsd     662   root  7u  IPv6   11108      0t0  TCP [::1]:631 (LISTEN)
cupsd     662   root  8u  IPv4   11109      0t0  TCP 127.0.0.1:631 (LISTEN)
rsyncd    905   root  4u  IPv4   13379      0t0  TCP *:873 (LISTEN)
...

Is there any way (without piping the output to another program, like grep, awk, or sed) to limit this to TCP sockets listening on the wildcard address? Tried:

$ lsof -Pni @0.0.0.0 -sTCP:LISTEN
lsof: incomplete Internet address specification: -i @0.0.0.0

and

$ lsof -Pni @\* -sTCP:LISTEN
lsof: unknown host name (*) in: -i @*

Alternatively, is there any way to generically negate the conditions passed to lsof?

benizi
  • 537

2 Answers2

1

Do you have to use lsof?

netstat -tulpn will show the processes that are listening on any given port. Processes listening on all IPs will show as 0.0.0.0:

gronostaj
  • 58,482
GeoSword
  • 254
0

This can't be done with lsof. There's no way to specify the wildcard address without matching just the wildcard:

lsof -nP -sTCP:LISTEN -i@0.0.0.0:1-65535

would seem to do it but it captures both the actual wildcard address (INADDR_ANY) as well as the semantic "wildcard", ie any address at all. Interestingly, [::] is not acceptable for a v6 wildcard selection. lsof does support negations but not for addresses, so eg you cannot do something to filter out localhost.

It can be done with ss(8) but the process name is difficult to parse.

# ss -nlt src 0.0.0.0
State    Recv-Q    Send-Q        Local Address:Port        Peer Address:Port
LISTEN   0         128                 0.0.0.0:22               0.0.0.0:*        users:(("sshd",pid=939,fd=3))

The part in "" (sshd above) is the process name, not the username as confusingly implied by the label.

IMO it would generally be easier to filter the lsof output than to parse the ss output. Or to process the output of /proc/net/tcp directly.