#!/usr/bin/perl
###############################################################################
# Name: count_ip.pl
# Author: Sam Tang
# Website: http://www.phpini.com/
# Purpose: read log file and print a report, display top tarffic ip, the ip
#          total access times and total access.
###############################################################################

use strict;
use warnings;
no warnings 'numeric';   # disable Argument "XXX" isn't numeric warning


my $line_num = 10;   ### default show top 10 records

if (!$ARGV[0]) {
    die  "Usage: count_ip.pl logfile [display lines]\n";
}

my $log = $ARGV[0];
$line_num = $ARGV[1] if ($ARGV[1]);


##### open log file, get the hostname and traffic
open(my $fh, '<', $log)
    or die "Could not open file '$log' $!";

my %ip;
my $total = 0;
##### save ip data to %ip
while (my $row = <$fh>) {
    if( $row =~ /(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/ ){
        $ip{$1}++;
        $total++;
    }
}


##### print top ip report
print "==================================\n";
print "    << IP Traffic Report: >>\n==================================\n";
my $start = 0;
foreach my $host (reverse sort { $ip{$a} <=> $ip{$b} } keys %ip) {
    if ($start < $line_num) {
        print $start+1 . ".";   ### print order number
        print " " if $start < 9;   ### add space for left align
        print " $host: $ip{$host}\n";   ### print data
    }
    $start++;
}
print "==================================\n";
print "     Total Access: $total\n";
print "==================================\n";
