Find number of active connections in Linux using various tools

1. Netstat
Netstat (network statistics) is a command-line network utility tool that displays network connections for the Transmission Control Protocol (both incoming and outgoing), routing tables, and a number of network interface (network interface controller or software-defined network interface) and network protocol statistics.
Using “netstat -a” will give you something sort of like this (this is a segment of my server):

tcp 0 0 app.mydomain.com:http 93.184.216.119:16494 SYN_RECV
tcp 0 0 app.mydomain.com:http 93.184.216.119:18733 SYN_RECV
tcp 0 0 app.mydomain.com:http 93.184.216.119.dsl.mwe:64775 SYN_RECV
tcp 0 0 app.mydomain.com:http 93.184.216.119.threembb.:16490 SYN_RECV
tcp 0 0 app.mydomain.com:http 93.184.216.119:video-activmail SYN_RECV
tcp 0 0 app.mydomain.com:http 93.184.216.119:45025 SYN_RECV
tcp 0 0 app.mydomain.com:http 93.184.216.119:dvl-activemail SYN_RECV
tcp 0 0 app.mydomain.com:http 41-135-22-100.dsl.mwe:64774 SYN_RECV

As you can see it does name resolving for us and all that good stuff. Sometimes very hand but that’s not what this is about. We want to get some solid numbers so we can take a broader perspective. To do this we can use the following command:

netstat -an | wc -l

Now, If we can check the No of Ips connected to port 80 . which is very helpful to detect the Ddos attack . the command is as under

netstat -tn 2>/dev/null | grep :80 | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -nr | head

Output – Total connections by IP, from highest to lowest.

97 114.198.236.100
56 67.166.157.194
44 170.248.43.76
38 141.0.9.20
37 49.248.0.2
37 153.100.131.12
31 223.62.169.73
30 65.248.100.253
29 203.112.82.128
29 182.19.66.187

If you would like to Watching active IP connections

watch -d -n1 ‘netstat -anp | grep -i stream’

2. SS
Socket statistics, or ss for short, is an easy replacement command for netstat. One way to use it, is with parameters ss -aut

-a: show listening and non-listening sockets
-u: show UDP
-t: show TCP

[[email protected] ~]# ss -aut
Netid State Recv-Q Send-Q Local Address:Port Peer Address:Port
udp UNCONN 0 0 *:bootpc *:*
tcp LISTEN 0 128 *:ssh *:*
tcp ESTAB 0 0 192.168.1.251:ssh 192.168.1.220:hnmp
tcp LISTEN 0 128 :::19531 :::*
tcp LISTEN 0 128 :::ssh :::*

This way it will show similar information to what netstat shows. When using it for very specific requests, you should refer to the man page, as it has some nice options.

Share This :

Leave a Reply

Your email address will not be published. Required fields are marked *