如何使用 Python 搭建一个 NTP 服务器
使用 python 基础库构建一个简易的 ntp 服务器,用来对移动设备进行时间的校准
服务端代码
这里需要注意的是,
struct
库的使用,用来将整型数据进行包装
import socket
import struct
import time
# Create a TCP/IP socket.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port.
server_address = ('0.0.0.0', 10000)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for incoming connections.
sock.listen(1)
TIME1970 = 2208988800
while True:
# wait for a connection.
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
reply = struct.pack('!I', int(time.time()) + TIME1970)
connection.sendall(reply)
except Exception:
pass
finally:
# Clean up the connection
connection.close()
客户端测试
这里使用 android 移动设备作为 ntp 客户端来进行测试
在上述服务启动之后,可以通过如下命令来执行测试
# 将 android 移动设备的时间设置为非当前时间
date 1230122018.59 set
# 使用 rdate 命令查看 ntp 服务端的时间
busybox rdate -p [your ntp server ip]:10000
# 使用 rdate 命令将客户端时间设置为服务端时间
busybox rdate -s [your ntp server ip]:10000