python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python搭建NTP服务器

如何使用Python搭建一个NTP服务器

作者:GettingReal

本文介绍了如何使用Python的基本库建立一个简单的NTP服务器,通过socket和struct处理网络连接和数据打包,以便对移动设备如Android进行时间校准,服务器端代码创建了一个监听TCP连接的socket,在接收到请求后发送当前时间信息,需要的朋友可以参考下

使用 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

到此这篇关于如何使用Python搭建一个NTP服务器的文章就介绍到这了,更多相关Python搭建NTP服务器内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文