【发布时间】:2018-06-04 21:00:48
【问题描述】:
获取网络时间协议数据包时(NTP 版本 4,请参阅here):
from contextlib import closing
from socket import socket, AF_INET, SOCK_DGRAM
import struct, time
start = time.time()
with closing(socket(AF_INET, SOCK_DGRAM)) as s:
s.sendto('\x23' + 47 * '\0', ('pool.ntp.org', 123)) # NTP v4, see RFC 5905
msg, address = s.recvfrom(1024)
now = time.time()
我通常会得到一个往返时间 now - start 大约 40 毫秒。
然而,与
format = "!4b4h9I"
unpacked = struct.unpack(format, msg[0:struct.calcsize(format)])
livnmode, stratum, poll, precision = unpacked[0:4]
print 'root_delay', unpacked[4] + float(unpacked[5]) / 2**16 # https://www.rfc-editor.org/rfc/rfc5905#page-13
print 'root_dispersion', unpacked[6] + float(unpacked[7]) / 2**16
print 'ref_id', unpacked[8]
print 'ref_timestamp %.3f' % (unpacked[9] + float(unpacked[10]) / 2**32 - 2208988800L)
print 'orig_timestamp %.3f' % (unpacked[11] + float(unpacked[12]) / 2**32)
print 'recv_timestamp %.3f' % (unpacked[13] + float(unpacked[14]) / 2**32 - 2208988800L)
print 'tx_timestamp %.3f' % (unpacked[15] + float(unpacked[16]) / 2**32 - 2208988800L
我得到一个 0.00056 秒的 root_delay,这似乎不太可能是真的! (我不认为我对时间服务器有 0.5 毫秒的 ping,往返时间......这真的太小了)
问题:root_delay 在 NTP 协议中究竟是如何测量的?
注意:
-
RFC 5905 声明:
Root Delay (rootdelay): Total round-trip delay to the reference clock, in NTP short format. -
我重新启动脚本的次数越多,
root_delay似乎就会减少(即使我的本地计算机 RTC 时间没有被我的 Python 脚本更新......这很奇怪......) -
我对@987654333@的解析似乎是正确的,见https://www.rfc-editor.org/rfc/rfc5905#page-19:
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |LI | VN |Mode | Stratum | Poll | Precision | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Delay | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Root Dispersion | ...和https://www.rfc-editor.org/rfc/rfc5905#page-13:
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Seconds | Fraction | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ NTP Short Format -
我不使用
ntplib似乎有不同的root_delay解析(但不符合https://www.rfc-editor.org/rfc/rfc5905#page-13?)
【问题讨论】: