Monitoring apache connections

If you run a more or less loaded apache web server, you will sooner or later happend to be in a situation that you need to know what ips are currently connected.

Here’s when netstat command comes in very handy.
To list all connections just issue:
netstat -a

Since apache uses TCP we can limit the output to TCP connection:
netstat -at

and we eliminate the dns lookup time overhead by adding another flag:
netstat -ant

Ok, this will list all the tcp connections. Next we want to only list connections belonging to apache. Apache’s binnary is called httpd and netstat with -p parameter will list socket owner’s process number and process name.

netstat -anpt|grep httpd

Now we have all sockets owned by apache. The problem is, that not all of them belong to currently connected users. We need to filter out only ESTABLISHED connections.

netstat -anpt|grep httpd|grep ESTABLISHED

Ok, almost there – now we use the cut utility to get only remote ips connected:
netstat -anpt|grep httpd|grep ESTABLISHED|cut -b45-60|cut -d’:’ -f1

Now we have only remote ips, but it can be a pretty long list and there will be duplicit ips listed. We will use uniq and sort commands to sort it by number of occurences of remote ip address:

netstat -anpt|grep httpd|grep ESTABLISHED|cut -b45-60|cut -d’:’ -f1|sort -rn|uniq -c|sort -t’ ‘ +1

If you wonder why there are 2 sorts – the first one is neccessary for uniq to filter out same lines, the second one orders the whole thing by number of ip occurences given by the output of uniq -c command.

Now you have nice sorted list of ips connecting to your web server at the current moment. Using watch command you can monitor the output for a longer time:

watch “netstat -anpt|grep httpd|grep ESTABLISHED|cut -b45-60|cut -d’:’ -f1|sort -rn|uniq -c|sort -t’ ‘ +1”


I am a g33k, Linux blogger, developer, student and Tech Writer for My passion for all things tech drives my hunt for all the coolz. I often need a vacation after I get back from vacation....

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.