download this file: ping.php view text/plain: ping.php file encoding: UTF-8 [goback]
<?php
##
## -- 2015.12.21: add mdev
## -- 2013.11.19: some
## -- 2011.07.22: new build
##
function icmp_result_print()
{
  global 
$icmp_i$icmp_c$icmp_t$icmp_p;
  global 
$ctime;

  
$avg = ($icmp_c>0) ? sprintf('%.3f',$icmp_t/$icmp_c) : '-';
  
$loss $icmp_i $icmp_c;
  
$cdate date('Y/m/d H:i:s',$ctime);
  
$mdev = @sprintf('%.3f',sqrt($icmp_p/$icmp_c pow($icmp_t/$icmp_c,2)));

  echo 
"$cdate $icmp_i packets transmitted, $icmp_c received, ${loss} packets loss, rtt avg = ${avg}ms, mdev = ${mdev}ms\n";
  
flush();
}

function 
_signo($signo)
{
  
icmp_result_print();
  if(
$signo != SIGHUP) exit(0);
}

require_once 
'class.icmp.php';

## ICMP ECHO: measure of lost-time(seconds)
##

set_time_limit(0);

if(
preg_match('/WIN/i',PHP_OS)) error_reporting(E_ALL E_NOTICE);
else
{
  declare(
ticks 1);
  
## 2 3 5 15 19 --> kill, 1 --> HUP
  ##
  
pcntl_signal(SIGHUP,'_signo'); // 1
  
pcntl_signal(SIGINT,'_signo'); // 2, Ctrl+C
  
pcntl_signal(SIGQUIT,'_signo'); // 3
  
pcntl_signal(SIGABRT,'_signo'); // 6
  //pcntl_signal(SIGKILL,'_signo'); // 9, it's fault
  //pcntl_signal(SIGUSR1,'_signo'); // 10, does not work
  
pcntl_signal(SIGALRM,'_signo'); // 14
  
pcntl_signal(SIGTERM,'_signo'); // 15
  //pcntl_signal(SIGSTOP,'_signo'); // 19, it's fault
}

if(!
$ip $_SERVER['argv'][1]) { echo 'type ip.address'; exit(1); }
if(
preg_match('/[a-z]/',$ip)) $ip gethostbyname($ip);

$icmp_i 0// icmp sequence idx
$icmp_t 0// icmp response OK total time
$icmp_p 0// icmp response OK total power time(for mdev)
$icmp_c 0// icmp response OK total count
$icmp_e 0// icmp error to OK count
$ms 0;
$usleep 1000000// 1sec

while(TRUE)
{
  if(
$ms 0)
  {
    
$sleepsec $usleep - ($ms*1000);
    if(
$sleepsec 0usleep($sleepsec);
  }
  else 
usleep($usleep);

  
$icmp_i++; // icmp sequence idx
  
$ctime time(); // current time

  
list($ms,$error) = icmp::ping($ip);

  if(
$error && ($ms<-1))
  {
    echo 
"ERROR: socket not create($error). run by root\n";
    exit(
1);
  }

  if(
$error$msg $error;
  else
  {
    list(
$rtt,$sent,$recv) = explode(' ',$ms);
    
//$icmp_latency = $rtt - $sent - $recv;
    
$msg "$rtt ms"// <= (sent=$sent + receive=$recv)";
    
$icmp_t += $rtt;
    
$icmp_p += $rtt*$rtt;
    
$icmp_c++;
  }

  
$cdate date('Y/m/d H:i:s',$ctime);
  echo 
"$cdate $ip icmp_seq=$icmp_i time=$msg\n";
}

exit(
0);
?>