python中的ntp客户端

How*_*ugh 14 python

我在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)
Run Code Online (Sandbox Code Playgroud)

Anu*_*pta 22

使用ntplib:

以下内容适用于Python 2和3:

import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))
Run Code Online (Sandbox Code Playgroud)

输出:

Fri Jul 28 01:30:53 2017
Run Code Online (Sandbox Code Playgroud)


Mic*_*ael 13

以下是对上述解决方案的修复,它为实现添加了几秒钟并正确关闭了套接字.因为它实际上只是一小撮代码,我不想在我的项目中添加另一个依赖项,尽管ntplib在大多数情况下可能是这样的.

#!/usr/bin/env python
from contextlib import closing
from socket import socket, AF_INET, SOCK_DGRAM
import sys
import struct
import time

NTP_PACKET_FORMAT = "!12I"
NTP_DELTA = 2208988800L # 1970-01-01 00:00:00
NTP_QUERY = '\x1b' + 47 * '\0'  

def ntp_time(host="pool.ntp.org", port=123):
        with closing(socket( AF_INET, SOCK_DGRAM)) as s:
            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()).replace("  "," ")
Run Code Online (Sandbox Code Playgroud)

  • 如果你想知道 `'\x1b' + 47 * '\0'` 代表什么: /sf/answers/1885695591/ (2认同)

Che*_*ngy 4

它应该是

msg = '\x1b' + 47 * '\0' 
Run Code Online (Sandbox Code Playgroud)

代替

msg = 'time'
Run Code Online (Sandbox Code Playgroud)

但正如 Maksym 所说,你应该使用 ntplib 代替。