Skip to content

Instantly share code, notes, and snippets.

@standa
Last active November 29, 2017 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save standa/09fb4bc9b50f346a1226d7b2cb7c6bf9 to your computer and use it in GitHub Desktop.
Save standa/09fb4bc9b50f346a1226d7b2cb7c6bf9 to your computer and use it in GitHub Desktop.
Error ping
<?php
/**
* @example Run as `php ping.php`
*
* Ping and keep pinging every 5 seconds.
*
* Print out only the errored packets
*/
namespace Maternia\Scripts;
const PING_IP = '8.8.8.8';
while (1) {
echo ($p = ping()) ? $p . PHP_EOL : '';
sleep(2);
}
function ping (string $ip = PING_IP, float $threshold = 500): ?string
{
$params = PHP_OS === 'Darwin' ? '--apple-time' : '';
$ping = exec("ping -c 1 $params $ip", $output, $status);
if ($status !== 0) {
return date('c').' error '.$status.': '.trim(end($output));
}
if (strpos($output[2], 'unreachable') !== false || strpos($output[2], 'timeout') !== false) {
return date('c').' unreachable/timeout: '.implode(PHP_EOL, $output);
}
// string(71) "13:50:07.498883 64 bytes from 8.8.8.8: icmp_seq=0 ttl=56 time=21.692 ms"
if (!preg_match('/([\d:\.]+).+time=([\d\.]+) ms/', $output[1], $m)) {
return date('c').': Invalid: '.$output[1];
}
if ($m[2] > $threshold) {
return date('c').': SLOW: '.$output[1];
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment