15 lsof -i examples to list network connections

The syntax:

lsof -i[46][protocol][@hostname|hostaddr][:service|port]

Run it as root or with sudo to be able to see all sessions. The options are case insensitive. For example, tcp or TCP are accepted.

TLDR: List all network connections and repeat it every second.

lsof -i -r1

1.List all network connections.

lsof -i

2.List all network connections without resolving IP and port number to names.

lsof -Pni

3.IPv4 only

lsof -i4

4.IPv6 only

lsof -i6

5.TCP only

lsof -i tcp

6.UDP only

lsof -i udp

7.List all network connections associated with a specific host.

lsof -i @IP_ADDRESS
lsof -i @HOSTNAME

8.List all network connections associated with a specific port.

lsof -i :PORT_NUMBER

Examples:

lsof -i :25
lsof -i :25,22
lsof -i :1-1023
lsof -i :ssh

Now, let’s combine the options.

9.List all connections related to TCP port 22.

lsof -i tcp:22

10.List all connections related to a host and a port.

lsof -i  @HOSTNAME:22

11.List all connections related to a host, a port and TCP.

lsof -i tcp@HOSTNAME:22

12.Repeat the command every 2 seconds whether or not there are matching sessions.

lsof -i tcp@HOSTNAME:22 -r2

13.Repeat that command every 2 seconds only as long as there are matching sessions.

lsof -i tcp@HOSTNAME:22 +r2

So far, we have not considered the state of the sessions whether they are listening, idle or closed. We can combine -i with -s [p:s] to include the state of the session.

14.List all TCP connections with state LISTEN

lsof -iTCP -sTCP:LISTEN 

15.List all TCP connections with state other than LISTEN

lsof -iTCP -sTCP:^LISTEN

According to the man page, these are the possible states:

State names vary with UNIX dialects, so it’s not possible to provide a complete list. Some common TCP state names are: CLOSED, IDLE, BOUND, LISTEN, ESTAB‐LISHED, SYN_SENT, SYN_RCDV, ESTABLISHED, CLOSE_WAIT, FIN_WAIT1, CLOSING, LAST_ACK, FIN_WAIT_2, andTIME_WAIT. Two common UDP state names are Unbound and Idle.

“lsof -iTCP -sTCP:LISTEN” doesn’t work for me. It complains “lsof: no UDP state names available: UDP:Idle”.

This means that this dialect of UNIX which is Linux, where I ran the command, does not support UDP state.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s