Count and Visualize Traffic Sources (by IP) using shell commands in Linux.

While suspecting to be victim of a DoS or DDoS Attack, could be useful to identify TOP Source of Connections.
This information can be retreived “On-The-Fly” by using some shell commands.

Order Client IPv4 address by Ascending number of connection (any Connection State) directed to [SERVER_IP:TCP:PORT]:

netstat -4nt |\
 grep "[SERVER_IP:TCP:PORT]" |\
 awk '{print $5}' |\
 cut -d: -f1 |\
 sort |\
 uniq -c |\
 sort -n

For example to monitor TCP connection on Port 443 for 62.212.12.109 (this blog):

netstat -4nt |\
 grep "62.212.12.109:443" |\
 awk '{print $5}' |\
 cut -d: -f1 |\
 sort |\
 uniq -c |\
 sort -n

Result will be formatted like this (example with masked IPs):

      1 62.94.xx.xx
      1 62.212.xx.xx
      3 62.94.xx.yy
      12 62.212.xx.yy

It is also possible to count IP Sources for traffic directed to apache2 process (only Established and Closing TCP connections in ESTABLISHED or FIN_WAIT2 status will be counted), by filtering netstat output in a different way:

netstat -4napt |\
 grep -v "0.0.0.0" |\
 grep "apache2" |\
 awk '{print $5}' |\
 cut -d: -f1 |\
 sort |\
 uniq -c |\
 sort -n

If no process information is needed and a global point of view is needed displaying ALL IPv4 TCP and UDP connection directed to the host (in any state), it is possible to use:

netstat -4ntu |\
 awk '{ if ( NR > 2  ) { print $5} }' |\
 cut -d: -f1 |\
 sort |\
 uniq -c |\
 sort -n

Comments are closed.