Show All TCP Connections with lsof

unix-tutorial-blue

I’ve spoken about lsof command briefly a few times, but think it deserves a few more mentions just because it’s such a universally useful tool.

Show TCP Connections with lsof

Using the –i tcp option, you can get lsof to report all the TCP connections currently open by any process in your system.

For example (it’s a long list so I’m just showing the first few lines):

greys@MacBook-Pro:/ $ lsof -i tcp | head -10
COMMAND     PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
cloudd      361 greys  197u  IPv4 0x90d8806378f8ff3d      0t0  TCP localhost:55919->localhost:nfsd-status (ESTABLISHED)
cloudd      361 greys  199u  IPv4 0x90d88063ab22823d      0t0  TCP localhost:65345->localhost:nfsd-status (ESTABLISHED)
rapportd    368 greys    3u  IPv4 0x90d8806374a56f3d      0t0  TCP *:65115 (LISTEN)
rapportd    368 greys    4u  IPv6 0x90d88063935504fd      0t0  TCP *:65115 (LISTEN)
rapportd    368 greys   11u  IPv4 0x90d8806378f91bbd      0t0  TCP macbook-pro.localdomain:65115->iphonex.localdomain:61268 (ESTABLISHED)
rapportd    368 greys   14u  IPv4 0x90d880637350a8bd      0t0  TCP macbook-pro.localdomain:65115->glebs-ipad-2.localdomain:59156 (ESTABLISHED)
SetappAge   555 greys    3u  IPv4 0x90d880637c43c53d      0t0  TCP localhost:codasrv (LISTEN)
SetappAge   555 greys    5u  IPv6 0x90d8806379b196fd      0t0  TCP localhost:codasrv (LISTEN)
Spillo      637 greys    9u  IPv4 0x90d880637350bbbd      0t0  TCP *:8490 (LISTEN)

Show TCP Connections of Specific Process

For individual processes, it’s easier to just show everything lsof can find about a process and then grep fot TCP.

I have an SSH session to one of my local systems:

greys@MacBook-Pro:/ $ ps -aef | grep ssh
501 11070 11053 0 8:35pm ttys008 0:05.59 ssh server

… so this lsof command example shows me that this process PID=11070 has TCP session open to ssh port (22) on server.localdomain server (MacOS adds localdomain everywhere):

greys@MacBook-Pro:/ $ lsof -p 11070 | grep TCP
ssh 11070 greys 3u IPv4 0x90d880638e66623d 0t0 TCP macbook-pro.localdomain:63830->server.localdomain:ssh (ESTABLISHED)

Pretty cool!

See Also