1

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
Pentium10
  • 444
  • 1
  • 9
  • 23

2 Answers2

1

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.

84104
  • 12,905
  • 6
  • 45
  • 76
  • Something is not OK here, as if I use my command above for port :9200 it lists for me several thousands, but your line, doesn't have anything about :9200 – Pentium10 Dec 18 '14 at 08:32
  • @Pentium10 This command covers **all** incoming ipv4 tcp ports. This is what you asked about, no? (Outgoing doesn't have anything useful to say grouped by port number, though it does when grouped by process.) I ran that line on one of my web proxy servers, which only listens on http and https. It sounds like your system listens on 9200. Given that you can't see why this matched the port your system list listening on, it seems that you don't understand regexp (regular expressions). Either trust blindly or learn. I recommend learning. Hint: `:9200` is matched by `(:[0-9]+)`. – 84104 Dec 18 '14 at 23:44
0

I'm sure there's a cleaner way to do this without double-awk'ing and double-grep'ing. (Hopefully someone can expound upon this)

Shell-based (ksh and bash) For-Loop

for x in $ (netstat -nat | grep TIME_WAIT | awk '{print $4}' | \
            awk -F":" '{print $2}' | sort -u) ; do
   printf "TIME_WAIT on Port $x : `netstat -nat|grep ":$x"|grep TIME_WAIT|wc -l`\n"
done

Output

TIME_WAIT on Port 42489 : 1
TIME_WAIT on Port 80 : 9
Signal15
  • 952
  • 7
  • 29