Thursday, January 9, 2014

如何檢測 Linux 的 open connection

Netstat is used to display network connections, routing tables and a whole bunch of network and interface stats.

·        lsof on the other hand is used to list out open files. So, if you want to find out what all files are currently open just run lsof.  And since in Linux "Everything is a File", we can use lsof to print network connections too.
Lets start learning by resolving common queries.

How to display a list of open ports?

This can be done using both netstat and lsof.
[shredder12]$ netstat -n -A inet
-n is used to display numeric addresses instead of trying to determine symbolic hostnames
-A is used to define the address family we are concerned with. Here its internet connections on IPv4 network, so inet(user inet6 for IPv6 connections).
[shredder12]$ lsof -i

How to display a list of Active connections?

In case you noticed the output of the command mentioned above, they actually show the active connections.
[shredder12]$ netstat -n -A  inet
[shredder12]$ lsof -i

How to display a list of listening ports?

Use the --listen flag with netstat to get a list.
[shredder12]$ netstat --listen -A inet

How to display a list of active TCP or UDP connections?

With netstat, we can use the flag -t to denote TCP connections only.
[shredder12]$ netstat -n -A inet -t
similarly, -u for UDP connections.
The -i flag of lsof provides a lot of configurable options. Use the following command to filter out TCP connections.
[shredder12]$ lsof -i4TCP
Please note no space between i4 and TCP. This means TCP connections on IPv4 network. Similary one can use i6 for IPv6 and UDP for udp connections.

How to find out all the ports being used by a single application or process using PID?

With netstat option -p you can even list out the program a port/socket is associated with. So, lets run -p with our active connections command and grep the pid.
[shredder12]$ netstat -A inet -n -p | grep 1413
You can find out the PID of a process using ps or pgrep.
[shredder12]$ ps -e | grep firefox
[shredder12]$ pgrep firefox

How to find out all the files being used by a program or application using PID?

Since we are concerned with files, lsof comes into play here. Here the -p option used along with the PID to catch the files associated with that process.
[shredder12]$ lsof -i4TCP -a -p 1413
The -a flag is used to tell lsof to AND the result of all the options used.