16
# lsof -n -itcp | wc
     92     919   10212

# lsof -n | grep TCP | wc
   2482   27222  373861

What I'm doing wrong with lsof -itcp ? Such calling is skipping part of connections, looks like this are connections of threads.

vector
  • 161
  • 1
  • 1
  • 3

2 Answers2

22

The correct syntax is:

lsof -a -i4 -i6 -itcp

This selects TCP sockets that are IPv4 or IPv6.

CodeWriter23
  • 321
  • 2
  • 6
1

Take a look at the two outputs. Here are samples from my system

lsof -n -itcp | head -4
COMMAND     PID        USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
rpcbind    1509        root    8u  IPv4   9013      0t0  TCP *:sunrpc (LISTEN)
rpcbind    1509        root   11u  IPv6   9016      0t0  TCP *:sunrpc (LISTEN)
rpc.statd  1537       statd    8u  IPv4  10059      0t0  TCP *:36035 (LISTEN)

lsof -n | grep TCP | head -4
rpcbind    1509             root    8u     IPv4               9013      0t0        TCP *:sunrpc (LISTEN)
rpcbind    1509             root   11u     IPv6               9016      0t0        TCP *:sunrpc (LISTEN)
rpc.statd  1537            statd    8u     IPv4              10059      0t0        TCP *:36035 (LISTEN)
rpc.statd  1537            statd   10u     IPv6              10063      0t0        TCP *:45203 (LISTEN)

A quick perusal shows that the only obvious differences so far is whitespace. This can be compared easily enough to find real differences:

lsof -n -itcp | sort >1
lsof -n | grep TCP | sort >2
diff -wu 1 2 | grep '^[+-]'
--- 1   2015-10-13 20:43:12.588658249 +0100
+++ 2   2015-10-13 20:43:18.272678740 +0100
-COMMAND     PID        USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
+dconf      3618 3634     roaima   11u     IPv6              12705      0t0        TCP [::1]:45177->[::1]:6010 (ESTABLISHED)
+gdbus      3632 3633     roaima    5u     IPv6              14008      0t0        TCP [::1]:45179->[::1]:6010 (ESTABLISHED)
+virt-mana  3618 3636     roaima   11u     IPv6              12705      0t0        TCP [::1]:45177->[::1]:6010 (ESTABLISHED)
+virt-mana  3618 3645     roaima   11u     IPv6              12705      0t0        TCP [::1]:45177->[::1]:6010 (ESTABLISHED)

Based on this output I'd suggest that the difference in my case is the IPv6 traffic. You might want to review your own situation but I suspect it's the same.

roaima
  • 107,089
  • 14
  • 139
  • 261