Skip to content

Instantly share code, notes, and snippets.

@leozhang2018
Created August 15, 2016 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leozhang2018/253153a920373e55aa52f8a65d156250 to your computer and use it in GitHub Desktop.
Save leozhang2018/253153a920373e55aa52f8a65d156250 to your computer and use it in GitHub Desktop.
Parsing-ping-results-php (Linux version:icmp_seq)
<?php
$pingTarget = "baidu.com";
$pingCount = 4;
//It's very important to escape shell arguments to avoid injection attacks.
$output = shell_exec('ping -c'.escapeshellarg((int)$pingCount).' '.escapeshellarg($pingTarget));
if(empty($output))
{
echo "An error occured. Most likely an invalid or unreachable domain.";
exit(1);
}
//This regex will grab each ping line.
$pingLineRegex = "/([0-9]+) bytes from (.+): icmp_seq=([0-9]+) ttl=([0-9]+) time=([0-9\.]+) ms/";
//This regex grabs the aggregated results at the bottom.
$pingResultRegex = $re = "/--- (.+) ping statistics ---\\n([0-9]+) packets transmitted, ([0-9]+) received, ([0-9\\.]+)% packet loss, time ([0-9]+)ms\\nrtt min\\/avg\\/max\\/mdev = ([0-9\\.]+)\\/([0-9\\.]+)\\/([0-9\\.]+)\\/([0-9\\.]+) ms/";
preg_match_all($pingLineRegex, $output, $pingLineMatches);
$pings = array();
//Array position 0 contains each matched line entirely. We use this to grab the count.
$pingCount = count($pingLineMatches[0]);
for($i=0;$i<$pingCount;$i++)
{
$pings[] = array(
'bytes' => $pingLineMatches[1][$i][0],
'host' => $pingLineMatches[2][$i][0],
'ip' => $pingLineMatches[3][$i][0],
'icmp_seq' => $pingLineMatches[4][$i][0],
'ttl' => $pingLineMatches[5][$i][0],
'time' => $pingLineMatches[6][$i][0],
);
}
preg_match_all($pingResultRegex, $output, $pingResultMatches);
$pingStatistics = array(
'host' => $pingResultMatches[1][0],
'tx' => $pingResultMatches[2][0],
'rx' => $pingResultMatches[3][0],
'loss' => $pingResultMatches[4][0],
'time' => $pingResultMatches[5][0],
'min' => $pingResultMatches[6][0],
'avg' => $pingResultMatches[7][0],
'max' => $pingResultMatches[8][0],
'mdev' => $pingResultMatches[9][0],
);
var_dump($pingLineMatches);
var_dump($pingStatistics);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment