Ping host measured in microseconds

Problem

You want to ping a host on a given port and record time taken in microseconds.

The following solution uses PHP socket libraries to open a connection, to the given host and port – then just close it again. By obtaining the microseconds before and after, it is able to deduce time taken in microseconds.

Additionally I’ve added functionality to print the epoch, so the timestamp can be obtained.



Solution

pingStat.php


<?php
list($usec, $sec)=explode(" ",microtime());
$thisDate=sprintf("%f", ($usec+$sec));
$host="$argv[1]";
$port="$argv[2]";

if(!$host) {
die("Usage: $0 host port [ dtg ]n");
}

$fp = fsockopen("$host", $port, $errno, $errstr, 30);
if (!$fp) {

print("ping failed to host: $host:$port -
$errstr ($errno)n");

} else {

list($usec, $sec)=explode(" ",microtime());
$nextDate=sprintf("%f", ($usec+$sec));

if($argv[3]) {
printf("%d:%0.4fn",time(),$nextDate-$thisDate);
} else {
printf("%0.4fn",$nextDate-$thisDate);
}

fclose($fp);

}

?>



Example


First example pings a host on port 80 and prints the current epoch.


$ php -q ./pingStat.php apachehost 80 y
1183524570:0.0824

Second example pings it again on port 443 and this time does not print epoch.


$ php -q ./pingStat.php apachehost 443
0.0775



Reference

[tags]Ping host measured in microseconds, PHP Coding School[/tags]



1 thought on “Ping host measured in microseconds”

Leave a Reply

Your email address will not be published. Required fields are marked *