~ Tinou /netmon.pl

#!/usr/bin/perl

$iface = "eth0";
$iface_file = "/tmp/.".$ENV{"USER"}.".netmon.iface";
$tmp_file = "/tmp/.".$ENV{"USER"}.".netmon.".$ENV{"DISPLAY"};
$nb_occ_avg = 15;
`touch $tmp_file`;
$log_size = `wc -l $tmp_file`;
if ($log_size <= $nb_occ_avg)
{
  $nb_occ_avg = $log_size;
}
  $precision = $nb_occ_avg + 1;
open(FD, '<', $iface_file);
$iface = <FD> or $iface = "eth0";
close(FD);
$arg = shift or $arg = "";
if ($arg =~ /toggle/)
{
  `rm -f $tmp_file`;
  $precision = 1;
  open(FD, '>', $iface_file);
  if ($iface =~ /eth0/)
  {
        $iface = "wlan0";
        print(FD "wlan0");
  }
  elsif ($iface =~ /wlan0/)
  {
        $iface = "eth0";
        print(FD "eth0");
  }
  close(FD);
}

$line = `grep $iface /proc/net/dev` or die ("impossible to open iface $iface");

if ($line =~ /$iface:\s*(\d+)\s+(\d+\s+){7}(\d+).*/)
{
  # grabbing the total bytes in and out
  $in_bytes[0] = $1;
  $out_bytes[0] = $3;
  # getting current time in seconds
  $time[0] = time();
  # opening temp file for reading : for the last time() and in and out total bytes
  # read
  open(FD, '<', $tmp_file);
  for ($i = 1; $i <= $precision ; $i++)
  {
        $last_line = <FD>;
        if ($last_line =~ /^(\d+)\s(\d+)\s(\d+)\s.*$/)
        {
          $time[$i] = $1;
          $in_bytes[$i] = $2;
          $out_bytes[$i] = $3;
        }
        else
        {
          $time[$i] = $time[($i > 1 ? $i - 1 : 0)];
          $in_bytes[$i] = $in_butes[($i > 1 ? $i - 1 : 0)];
          $out_bytes[$i] = $out_bytes[($i > 1 ? $i - 1 : 0)];
        }
  }
  close(FD);
  $elaps = $time[0] - $time[$precision - 1];
# lets avoid dividing by zero
  if ($elaps != 0)
  {
        $in_rate = ($in_bytes[0] - $in_bytes[$precision - 1]) / $elaps;
        $out_rate = ($out_bytes[0] - $out_bytes[$precision - 1]) / $elaps;
  }
  else
  {
        $in_rate = 0;
        $out_rate = 0;
  }
# converting bytes to kbytes
  $in_rate = $in_rate / 1024;
  if ($in_rate >= 1024)
  {
        $in_unit = "Mb/s";
        $in_rate = $in_rate / 1024;
  }
  else
  {
        $in_unit = "kb/s";
  }
  $out_rate = $out_rate / 1024;
  if ($out_rate >= 1024)
  {
        $out_unit = "Mb/s";
        $out_rate = $out_rate / 1024;
  }
  else
  {
        $out_unit = "kb/s";
  }
  # write
  open(FD, '>', $tmp_file);
  for ($i = 0; $i <= $precision ; $i++)
  {
        $new_line = $time[$i]." ".$in_bytes[$i]." ".$out_bytes[$i]."\n";
        print(FD $new_line);
  }
  close(FD);

  printf("%s[%d]: down:%6.2f %s, up:%6.2f %s", $iface, $elaps, $in_rate, $in_unit, $out_rate, $out_unit);
}