0

Using lsof command I would like to print out TCP connections with ESTABLISHED state but ignoring the ones with localhost.

I tried:

lsof -itcp@^127.0.0.1 -stcp:established
lsof -itcp@(^127.0.0.1) -stcp:established
lsof -itcp -i ^@127.0.0.1 -stcp:established

and others similar, but always getting sintax error response.

What is correct sintax?

  • 1
    Try using ss -tlpn -o state ESTABLISHED This is much better than lsof for what you want. – Valentin Bajrami Dec 13 '23 at 19:34
  • Or while at it as a Linux-only method: ss -4tnp state established not dst 127.0.0.0/8 . @ValentinBajrami btw: -l is incompatible with state established (because it means state listening). – A.B Dec 13 '23 at 19:43
  • @A.B on that's so true. Wasn't even thinking since I usually type ss -tlpen... most of the time. Good pointers and not dst 127.0.0.0/8 is definitely what's needed here. – Valentin Bajrami Dec 13 '23 at 20:06

1 Answers1

4

It doesn't look like you can negate network addresses in lsof.

If on Linux, you could use lsfd from util-linux instead:

lsfd -Q '(type =~ "^TCP") and
         (name =~ "state=established") and
         (name !~ "addr=(\[::1\]|127)")'

Or as mentioned by @A.B ss from iproute2:

ss -tp state established not dst 127.0/8 not dst '[::1]'