Linux – Netstat count TIME_WAIT connections by port

centoslinuxnetstatshell

I can obtain individual TIME_WAIT counts on a port,

netstat -nat | grep :11300 | grep TIME_WAIT | wc -l;

but how to do this based on all ports eg:

11300   2900 connection
3306    1200 connection
80      890 connection

Best Answer

These days I send to use sed for this type of thing.

$ netstat -nt | sed -r -n 's/^tcp +[0-9]+ +[0-9]+ [0-9\.]+(:[0-9]+).+TIME_WAIT/\1/p' | sort | uniq -c | sort -n
      5 :443  
      8 :80

Here we are interesting in a line that looks a specific way, but really one piece out of it. So we define the regex with a match group for that part and then print only the matching piece of lines that we care about. I haven't found a better way around sort | uniq -c. The last sort is for aesthetics and utility.

Related Topic