Last active
December 15, 2015 15:08
-
-
Save keiya/5279076 to your computer and use it in GitHub Desktop.
Simple Traffic Monitor (ifconfig, perl)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/perl | |
| # by Keiya Chinen <[email protected]> | |
| use strict; | |
| use warnings; | |
| $ENV{'LANG'} = 'C'; | |
| $| = 1; | |
| my $format = '%.3f'; | |
| my ($lastRx,$lastTx,$totalRx,$totalTx,$isInit); | |
| my ($calibrationRx,$calibrationTx) = (0,0); | |
| my $interface = $ARGV[0] || 'eth0'; | |
| printf ("%10s %10s %10s %10s \n","RX Rate","TX Rate","RX Bytes","TX Rates"); | |
| while (1) { | |
| my @ifconfig = split("\n",`ifconfig $interface`); | |
| foreach my $line (@ifconfig) { | |
| if ($line =~ /RX bytes:(\d+) .+TX bytes:(\d+)/) { | |
| my ($deltaRx,$deltaTx) = (0,0); | |
| my ($Rx,$Tx) = ($1,$2); | |
| my $cRx = $Rx + $calibrationRx; | |
| my $cTx = $Tx + $calibrationTx; | |
| if (!$isInit) { | |
| $totalRx = $Rx; | |
| $totalTx = $Tx; | |
| $isInit = 1; | |
| } | |
| else { | |
| $deltaRx = $Rx - $lastRx + $calibrationRx; | |
| $deltaTx = $Tx - $lastTx + $calibrationTx; | |
| $totalRx += $deltaRx; | |
| $totalTx += $deltaTx; | |
| } | |
| my $deltaRxH = format_human_readable($deltaRx,$format); | |
| my $deltaTxH = format_human_readable($deltaTx,$format); | |
| my $totalRxH = format_human_readable($totalRx,$format); | |
| my $totalTxH = format_human_readable($totalTx,$format); | |
| printf ("%10sB/s %10sB/s %10sB %10sB\r",$deltaRxH,$deltaTxH,$totalRxH,$totalTxH); | |
| $lastRx = $Rx; | |
| $lastTx = $Tx; | |
| } | |
| } | |
| sleep 1; | |
| } | |
| sub format_human_readable { | |
| my $K = 1000; | |
| my $M = $K * 1000; | |
| my $G = $M * 1000; | |
| my $T = $G * 1000; | |
| if ($_[0] < $K ) { | |
| return $_[0]; | |
| } | |
| elsif ($_[0] >= $K && $_[0] < $M) { | |
| return sprintf($_[1].'K',$_[0]/$K); | |
| } | |
| elsif ($_[0] >= $M && $_[0] < $G) { | |
| return sprintf($_[1].'M',$_[0]/$M); | |
| } | |
| elsif ($_[0] >= $G && $_[0] < $T) { | |
| return sprintf($_[1].'G',$_[0]/$G); | |
| } | |
| elsif ($_[0] >= $T) { | |
| return sprintf($_[1].'T',$_[0]/$T); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment