7

Display the number of connections per IP to port 80

while true; do clear; date; echo; echo "[Count] | [IP ADDR]"; echo "-------------------"; netstat -n | grep ':80\>' | awk '! /LISTEN/ {print $5}' | cut -d: -f1 | uniq -c; sleep 5; done

April 9, 2014cesp

Explanation

while true; do ...; done is an infinite loop.

We repeated do:

  • clear -- clear the screen
  • date -- print the current date
  • echo -- print a blank line
  • echo "[Count] | [IP ADDR]"; echo "-------------------" -- print a heading
  • And finally the connection stats using netstat, processed with some tools.

netstat -n prints various statistics about current network connections. The -n flag makes it use numeric values instead of names, for example IP address instead of hostname, and port number instead of port name (such as 22 instead of ssh).

With grep ':80\>' we filter out the lines that have :80, such that :80 is at the end of a word. That is, if we simply used the pattern :80 without the \>, that would match :8009 too, which we don't want now. To make sure that no other digits follow after :80, we use the pattern :80\>.

We further process this with awk '! /LISTEN/ {print $5}', matching only lines that do not contain LISTEN, and we print the 5th column, which is in the format IP_ADDRESS:PORT_NUMBER.

To get just the IP address part, we use cut -d: -f1 to get the first column, using : as the delimiter.

We use uniq -c to get the count of the repeated lines, in this example the count of each unique IP address.

Finally we sleep for 5 seconds with sleep 5.