To View the number of active tcp connections to a server based on IP address, sorted from lowest to highest
netstat -anp | grep tcp | awk '{print $5}' | cut -f 1 -d : | sort | uniq -c | sort -n
Comparing that to the following might be instructive for some folks. Check out the differences.
Code:
netstat -tn | tail -n+3 | awk {print\$5} |cut -d: -f1|sort|uniq -c|sort -nr
We didn't need to use grep tcp, because netstat has a -t option; we also didn't need to use -p since we weren't selecting for programs; and since we don't want to see listening things, we don't need -a. Then all the rest is the same except that I reversed the sort order at the end.
Personally, I'm partial to lsof. It's much more powerful than netstat, IMO. I also would want to see ports as well. I'm no expert, but here's what I came up with:
Code:
lsof -nPi tcp -F n | awk -F\> '/>/{print$2}'| sort | uniq -c | sort -nr
which gives some output like:
Code:
3 74.125.39.104:443
2 209.85.229.125:5222
1 92.123.159.139:443
1 74.125.236.147:443
1 74.125.230.142:443
1 74.125.230.137:80
1 74.125.230.128:80
1 69.171.229.11:443
1 209.85.147.83:443
Breaking down
lsof -nPi tcp -F n:
-n &
-P stop host & port lookups
-i selects for internet "files" and the optional arg of
tcp, well.. that's obvious
-F makes lsof run in a special mode designed for passing to other programs; in this case we tell it with
n that we only want to see the name/netaddress field (but it shows us the pid anyway)
Breaking down
awk -F\> '/>/{print$2}'
Awk is amazing. I'm a novice with it, but I still find it quite useful. Case in point, almost everyone has to use awk for column selection at some point, but I think a lot basic cmdline users don't realize that it can do searching & column selection in one fell-swoop (instead of chaining it with grep). The syntax is super simple: awk '/regex searchstring/{print $FIELD#}'
So in our case, we're simply search for
> and printing the second column. BUT WAIT--we also ran with an arg of
-F\>, which tells awk to use a field-separator of
> (had to escape for the shell of course).
Here's a small taste of what awk can do. Run it as root to check it out. I put this together a little while back, as part of a script that reports hardware info.
Code:
dmidecode -t memory|awk '/^[[:space:]]Size: [[:digit:]]/{numdims+=1;ram=$2;sumram+=ram}END{print numdims" DIMMs, "sumram" MB actual"}'
which prints out something like this if you have dmidecode (program for querying info from the bios) installed:
Hope someone finds all this instructive!
Oh, PS: For more on lsof, I just posted about it a little while ago
here.