download this file: event.ntp-time_server_offset.php view text/plain: event.ntp-time_server_offset.php file encoding: UTF-8 [goback]
<?php
##
##
## http://www.faqs.org/rfcs/rfc2030.html
##
## ntpdate -u time.bora.net // firwall bypass
## ntpdate -ub time.bora.net // at boot
## ntpdate -uq time.bora.net // only print
##
## [study]
## Timestamp Name ID When Generated
## ------------------------------------------------------------
## Originate Timestamp T1 time request sent by client
## Receive Timestamp T2 time request received by server
## Transmit Timestamp T3 time reply sent by server
## Destination Timestamp T4 time reply received by client
##
## The roundtrip delay d and local clock offset t are defined as
##
## d = (T4 - T1) - (T2 - T3) t = ((T2 - T1) + (T3 - T4)) / 2.
##
##
## [changes]
## - 2013.12.05: new build, by san2@2013.12.05
##
function get_microtime2float()
{
list($sf,$ss) = explode(' ',microtime());
return sprintf('%.4f',$ss+$sf); // float
}
$_DEBUG = FALSE;
$tss = array('time.bora.net:37'); // TCP/37 server
$tsc = sizeof($tss);
for($i=0; $i<$tsc; $i++)
{
$time_server_info = trim($tss[$i]);
list($time_server,$port) = explode(':',$time_server_info);
$fp = @fsockopen($time_server,$port,$errno,$errstr,10);
if(!$fp) { echo "$time_server TCP/$port: $errstr ($errno)\n"; continue; }
$data = '';
while(!feof($fp))
{
//$T1 = get_microtime2float();
$data .= fgets($fp,128);
//$T4 = get_microtime2float();
}
$T1 = get_microtime2float(); // to last
@fclose($fp);
// we have a response...is it valid? (4 char string -> 32 bits)
if(strlen($data) != 4)
{
echo "$time_server TCP/$port returned an invalid response.\n";
continue;
}
## debug
##
if($_DEBUG)
{
$s = strlen($data);
for($i=0; $i<$s; $i++) echo "DEBUG.received.data: : $i => ".ord($data[$i])."\n";
}
$ntptime = ord($data{0})*pow(256,3) + ord($data{1})*pow(256,2) + ord($data{2})*256 + ord($data{3});
## convert the seconds to the present date & time
## 2840140800 = Thu, 1 Jan 2060 00:00:00 UTC
## 631152000 = Mon, 1 Jan 1990 00:00:00 UTC
##
$ntptime += 631152000 - 2840140800;
//$localtime = ($T1 + $T4) / 2;
$localtime = $T1;
$offset = sprintf('%.1f',($ntptime-$localtime)*1000); // ms
if($offset > 0) $offset = '+'.$offset;
printf("%-20s: %-20s\n",$time_server_info,date('Y-m-d H:i:s',$ntptime));
printf("%-20s: %-20s\n",'LOCAL.TIME',date('Y-m-d H:i:s',$localtime));
printf("%-20s: %-20s\n",'offset',$offset.' ms');
}
exit;
?>