[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.
[/problem]
[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);
}
?>
[/solution]
[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
[/example]
[reference]
[tags]Ping host measured in microseconds, PHP Coding School[/tags]
[/reference]