如何获取NTP有效负载数据字节

问题描述

我有一段代码来接收ntp计时

from socket import AF_INET,SOCK_DGRAM # For setting up the UDP packet.
import sys
import socket
import struct,time # To unpack the packet sent back and to convert the seconds to a string.

host = "pool.ntp.org"; # The server.
port = 123; # Port.
read_buffer = 1024; # The size of the buffer to read in the received UDP packet.
address = ( host,port ); # Tuple needed by sendto.
#data = '\x1b' + 47 * '\0'; # Hex message to send to the server.
data = [0x1b]

temp = [0x00 for i in range(47)]

data.extend(temp)

epoch = 2208988800 # Time in seconds since Jan,1970 for UNIX epoch.

client = socket.socket( AF_INET,SOCK_DGRAM ); # Internet,UDP

client.sendto(bytes(data),address ); # Aend the UDP packet to the server on the port.

dataRx,address = client.recvfrom( read_buffer ); # Get the response and put it in data and put the send socket address into address.

t = struct.unpack( "!12I",dataRx)[ 10 ]; # Unpack the binary data and get the seconds out.

t -= epoch; # Calculate seconds since the epoch.

print("Time = {0}".format(time.ctime( t ))) # Print the seconds as a formatted string

基于此处给出的代码

https://github.com/lettier/ntpclient/blob/master/source/python/ntpclient.py

如果我看到收到的数据:

数据接收

b'\x1c\x02\x03\xe7\x00\x00\x02\x89\x00\x00\x00\x10\xc1O\xed\x0e\xe3\xecP\xea_u\x93\xc8\x00\x00\ x00\x00\x00\x00\x00\x00\xe3\xecP\xf5\xd1D\x84\xdf\xe3\xecP\xf5\xd1F+\x1f'。

问题 1:

dataRx 中的“xecP\xea_u”部分是什么?为什么 dataRx 中存在非十六进制字符?

问题 2:

如何获取十六进制格式的NTP计时字节(64位)?

解决方法

您可以自己解压 NTP 数据包,但建议查看 ntplib python 模块,该模块发出 NTP 请求、解码数据包等。ntplib 请求提供对 NTP 响应数据包每个字段的访问。

已经根据响应计算了往返延迟和时间偏移。 ntplib 是在 2009 年创建的,并且在此答案中仍然处于活动状态并得到维护。

如果您对详细信息感兴趣,请查看 ntplib.py source code

import ntplib

client = ntplib.NTPClient()
server = 'pool.ntp.org'

resp = client.request(server,version=3)

print("offset",resp.offset)
print("delay",resp.delay)

print("orig_time:",datetime.utcfromtimestamp(resp.orig_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
print("recv_time:",datetime.utcfromtimestamp(resp.recv_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
print("tx_time  :",datetime.utcfromtimestamp(resp.tx_time).strftime('%Y-%m-%d %H:%M:%S.%f'))
print("dest_time:",datetime.utcfromtimestamp(resp.dest_time).strftime('%Y-%m-%d %H:%M:%S.%f'))

输出:

offset 0.004678010940551758
delay 0.06687116622924805

orig_time: 2021-06-10 19:07:52.410973
recv_time: 2021-06-10 19:07:52.449087
tx_time :  2021-06-10 19:07:52.449089
dest_time: 2021-06-10 19:07:52.477846