#!/usr/bin/perl

use warnings;
use vars;
use strict;

######## CONFIGURATION ###########
my $host="64.233.183.147";
my $dst_port=80;
my $src_port=55555;
my $pkt_to_send=4;
my $tmp_file="/tmp/check_hping.tmp";
my $file;
my $counter_recived=0;
my $counter_bad=0;
my $bad_response="";
my $rtt=0;
my $rtt_m=0;
my $row="";
my $hping="/usr/sbin/hping3";
###################################

# executing hping and saving result in a file 
system("$hping -S $host -p $dst_port -s $src_port -c $pkt_to_send >  $tmp_file 2>&1");

# reading the result file line by line 
open(FILE, $tmp_file) || die "hermessWSG VPN CRITICAL: impossibile aprire il file!!!"; 

while ($row=<FILE>) {
   if ($row =~ m/.*flags=(\w{1,3}).*rtt=(\d*\.\d) ms/) { 
      $counter_recived++;
      if ($1 ne "SA") { $counter_bad++; $bad_response.="$1 / "; }
      $rtt=$rtt+$2; 
      }
}

close(FILE);
unlink($tmp_file);

# avoiding division by 9 
if ($counter_recived != 0) { $rtt_m=$rtt/$counter_recived; } else { $rtt=0; }
my $msg="rtt medio: $rtt_m; ricevuti $counter_recived/$pkt_to_send; non-ack $counter_bad ($bad_response)";

# return code for Nagios 
# 0 = OK
# 1 = WARNING 
# 2 = CRITCAL

if ( $counter_recived == 0 ) { print "$host CRITICAL: no packets recived"; exit 2 }
if ( ($counter_bad == 1) || ( $counter_recived < $pkt_to_send ))   
                             { print "$host WARNING: $msg";                exit 1 }
elsif ( $counter_bad >= 2 )  { print "$host CRITICAL: $msg";               exit 2 }
else                         { print "$host OK: $msg";                     exit 0 };
