Search code examples
linuxnetwork-programmingubuntu-12.04tcpdumpnetstat

Getting count of open connections


I have automated the deployment of my application via fabric and have a new step that I need to add where I take my application out of rotation in the load balancer then, watch inbound connections from the balancer until they go to 0. Problem is, I am not sure how to get the count of inbound connections.

I can use tcpdump to watch my port POSTs. However, this is kind of hard to use in fabric. What I would like is to just run a loop with a timer that keeps getting the number of active inbound connections and exits on 0. Has anybody done anything like this? Or maybe someone would know how I might be able to achieve this from the shell and I can put it in fabric?


Solution

  • netstat is one of the simplest ways to get this information, however, as you have noted, simply using grep to parse the output of netstat yields sub-optimal results, because it will match both incoming and outgoing connections (at least without a sufficiently complex search expression, or preprocessing with cut or the like). I would suggest this route, instead:

    netstat -ap | awk '$1 == "tcp" && $4 ~ /:(80|443)$/' | wc -l
    

    This will count connections that are TCP-based, and the local end is connected to either port 80 or 443, which would correspond with incoming connections. Replace $4 with $5 in that to catch outgoing connections instead.