我用python编写了一个ntp客户端来查询时间服务器并显示时间,程序执行但没有给我任何结果。 我使用的是python的2.7.3集成开发环境,我的操作系统是Windows 7。 这是代码:
# File: Ntpclient.py
from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time
# # Set the socket parameters
host = "pool.ntp.org"
port = 123
buf = 1024
address = (host,port)
msg = 'time'
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00
# connect to server
client = socket.socket( AF_INET, SOCK_DGRAM)
client.sendto(msg, address)
msg, address = client.recvfrom( buf )
t = struct.unpack( "!12I", data )[10]
t -= TIME1970
print "\tTime=%s" % time.ctime(t)
使用ntplib:
以下内容应该适用于 Python 2 和 3:
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))
输出:
Fri Jul 28 01:30:53 2017
这里是对上述解决方案的修复,它增加了实现时间并正确关闭套接字。因为它实际上只是几行代码,所以我不想向我的项目添加另一个依赖项,尽管
ntplib
不可否认,在大多数情况下可能是正确的方法。
#!/usr/bin/env python
from contextlib import closing
from socket import socket, AF_INET, SOCK_DGRAM
import struct
import time
NTP_PACKET_FORMAT = "!12I"
NTP_DELTA = 2208988800 # 1970-01-01 00:00:00
NTP_QUERY = b'\x1b' + 47 * b'\0'
def ntp_time(host="pool.ntp.org", port=123):
with closing(socket( AF_INET, SOCK_DGRAM)) as s:
s.settimeout(5)
s.sendto(NTP_QUERY, (host, port))
msg, address = s.recvfrom(1024)
unpacked = struct.unpack(NTP_PACKET_FORMAT,
msg[0:struct.calcsize(NTP_PACKET_FORMAT)])
return unpacked[10] + float(unpacked[11]) / 2**32 - NTP_DELTA
if __name__ == "__main__":
print(time.ctime(ntp_time()))
应该是
msg = '\x1b' + 47 * '\0'
而不是
msg = 'time'
但正如 Maksym 所说,你应该使用 ntplib 来代替。
msg = '\x1b' + 47 * '\0'
.......
t = struct.unpack( "!12I", msg )[10]