#!/bin/bash -
#===============================================================================
#
#          FILE: traffic
#
#         USAGE: traffic <network interface> [loop]
#
#   DESCRIPTION: Monitor network traffic and packets.
#
#  REQUIREMENTS: ifconfig
#        AUTHOR: rickz (Rick Zhang), xlrickz@gmail.com
#       COMPANY: X-LEGEND Entertainment Corp.
#       CREATED: Sun Jun 26 22:52:42 EDT 2011
#      REVISION: 1.0
#===============================================================================

#set -o nounset                              # Treat unset variables as an error
#set -m                                      # Enable job control

[ "$1" == "" ] && exec echo "Usage: traffic <network interface> [loop]

Please specify a network interface:
$(sed 's/:/ /g' /proc/net/dev|awk '/[0-9][0-9]/ {print $1" "$2" "$3" "$10" "$11}'|awk '{print $1}')"

INTERFACE="$1"
CONNECTIONS="$(netstat -napt 2>&1| grep "$(ifconfig $INTERFACE | grep "inet addr:" | sed 's/:/ /g' | awk '{print $3}')" | grep ESTABLISHED | wc -l)"

[ "$2" == "loop" ] \
&& echo    "Total $CONNECTIONS TCP connections." \
|| echo -n "Total $CONNECTIONS TCP connections, "

eval $(sed 's/:/ /g' /proc/net/dev|awk '/'"$INTERFACE"'.*[0-9]$/ {print "export RECEIVE_BYTES="$2";export RECEIVE_PACKETS="$3";export TRANSMIT_BYTES="$10";export TRANSMIT_PACKETS="$11}')  

while true;do 
   TIME="$(date +"%Y/%m/%d %H:%M:%S") "
   sleep 1s
   OLD_RECEIVE_BYTES=$RECEIVE_BYTES
   OLD_RECEIVE_PACKETS=$RECEIVE_PACKETS
   OLD_TRANSMIT_BYTES=$TRANSMIT_BYTES
   OLD_TRANSMIT_PACKETS=$TRANSMIT_PACKETS
   eval $(sed 's/:/ /g' /proc/net/dev|awk '/'"$INTERFACE"'.*[0-9]$/ {print "export RECEIVE_BYTES="$2";export RECEIVE_PACKETS="$3";export TRANSMIT_BYTES="$10";export TRANSMIT_PACKETS="$11}')

   [ "$TIME" == "$(date +"%Y/%m/%d %H:%M:%S") " ] && exit

   echo -en "$(date +"%Y/%m/%d %H:%M:%S")\t"
   echo -en "Receive: $((($RECEIVE_BYTES-$OLD_RECEIVE_BYTES)/1024*8)) kbps($(($RECEIVE_PACKETS-$OLD_RECEIVE_PACKETS)) packet/s)  \t"
   echo -e  "Transmit: $((($TRANSMIT_BYTES-$OLD_TRANSMIT_BYTES)/1024*8)) kbps($(($TRANSMIT_PACKETS-$OLD_TRANSMIT_PACKETS)) packet/s) "

   [ "$2" == "loop" ] || break
done
true

