title: Script to count number of connections using a range of TCP ports
body: <p>I am using the following script to count the number of connections in established, and time wait state for a specific range of TCP ports.</p>
  
  <p>The script uses netstat and egrep to try and filter out valid connections.  The script also reads input from a file and counts the number of connections observed.</p>
  
  <pre><code>#!/bin/bash
  START=121
  END=9089
  
  [ -f /tmp/ports.txt ] &amp;&amp; rm -f /tmp/ports.txt
  
  for ((a=$START; a &lt;= $END; a++)); do
      netstat -an | nawk '/TIME_WAIT|ESTABLISHED/ &amp;&amp; !/127.0.0.1/{split($4,a,".");print a[5]}' | egrep -c ^${a}$ | \
      awk -v x=$a '\
      $0 != 0 {printf("%d %d\n",x,$0)}' | tee -a /tmp/ports.txt
  done
  
  awk -v s=$START -v e=$END '\
      BEGIN{t=0}
      {t=t+$2}
      END{printf("\nTotal Connections on ports %d-%d: %d\n",s,e,t)}' /tmp/ports.txt
  
  rm -f /tmp/ports.txt
  </code></pre>
  
  <p>I'm looking for ways to improve the performance of the script.  With the current range of ports (121-9089) it takes about 77 seconds to finish.</p>
  
  <p>I'm looking for suggestions for improving the performance along with an example script.</p>