gpt4 book ai didi

python - 简单的 SNTP python 脚本

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:25 29 4
gpt4 key购买 nike

我需要帮助来完成以下脚本:

import socket
import struct
import sys
import time

NTP_SERVER = '0.uk.pool.ntp.org'
TIME1970 = 2208988800L

def sntp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = str.encode('\xlb' + 47 * '\0')
client.sendto(data, (NTP_SERVER, 123))
data, addr = client.recvfrom(1024)
if data:
print('Response received from:', addr)
t = struct.unpack('!12I', data)[10]
t -= TIME1970
print('\tTime: %s' % time.ctime(t))

if __name__ == '__main__':
sntp_client()

预期输出:

Response received from: ('80.82.244.120', 123)
Time: Tue Sep 13 14:49:38 2016

问题是程序没有给出任何输出。看起来它停留在:

data, addr = client.recvfrom(1024)

我希望有人能帮我解决这个问题。

最佳答案

这是 Python Network Programming Cookbook第二版 的工作脚本:

import socket, struct, sys, time

NTP_SERVER = '0.uk.pool.ntp.org'
TIME1970 = 2208988800

def sntp_client():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data = '\x1b' + 47 * '\0'
client.sendto(data.encode('utf-8'), (NTP_SERVER, 123))
data, address = client.recvfrom(1024)
if data: print('Response received from:', address)
t = struct.unpack('!12I', data)[10] - TIME1970
print('\tTime = %s' % time.ctime(t))

if __name__ == '__main__':
sntp_client()

关于python - 简单的 SNTP python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39466780/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com