Often we have good reasons to ask, who is connecting to our server or what process is using which port? There are some simple ways to verify that. A good start is always the NETSTAT command.
netstat -tn tcp 0 0 10.10.10.228:46057 74.125.135.139:443 ESTABLISHED tcp 0 0 10.10.10.228:44840 64.91.231.216:80 TIME_WAIT tcp 0 0 10.10.10.228:52012 23.10.17.224:80 ESTABLISHED tcp 0 0 10.10.10.228:44868 64.91.231.216:80 TIME_WAIT
With the option ‘t’ we only display TCP connection and ‘n’ is for numeric only – avoid name resolution. We can make this of course easier to read and just use some of the Linux shell goodies:
netstat -tn | grep :80 | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr 9 117.211.24.45 8 127.0.0.21 6 112.198.82.215 3 5.10.83.103 3 203.81.72.87 1 66.249.77.46
Here we see only connections to port 80, all unwanted information stripped off and even the number of active connection in front of every IP.
Another good thing to know, which process is listening on which port. Especially when a host is under suspicion to have been hacked:
netstat -aptn|grep LISTEN tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 2387/sshd tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 1632/cupsd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 3629/master tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 3163/mysqld tcp 0 0 :::22 :::* LISTEN 2387/sshd tcp 0 0 :::631 :::* LISTEN 1/init tcp 0 0 ::1:25 :::* LISTEN 3629/master tcp 0 0 :::445 :::* LISTEN 2467/smbd tcp 0 0 :::8383 :::* LISTEN 18927/java tcp 0 0 127.0.0.1:8008 :::* LISTEN 18927/java tcp 0 0 :::139 :::* LISTEN 2467/smbd tcp 0 0 ::1:44654 :::* LISTEN 18927/java tcp 0 0 :::80 :::* LISTEN 2490/httpd2-prefork
The ‘a’ shows all network connections, the parameter ‘t’ limits it to TCP only . With the ‘n’ parameter we are avoiding the known ports to be translated into text (e.g. 22 to SSH). Finally the ‘GREP LISTEN’ makes sure to only show the interesting part of the whole output – which processes are listening to a port.
Another approach would be to use LSOF, it can also show open network connections:
lsof -i tcp|grep LISTEN
I prefer netstat, as you can find it on all systems. Same does not necessarily apply for lsof.