NTP client
I used to sync my computer’s time using a script called httptime. httptime is a script that fetches the current date and time by making HTTP requests and reading the Date
response header.
This worked pretty well, and I’d still consider it a good solution. But I also wanted to use what everyone else uses for time sync, which is NTP (Network Time Protocol).
I read through the RFCs, and it seems pretty simple to use. You send one UDP packet to an NTP server, you get another packet back. And that packet contains the current timestamp.
To pick a random NTP server, I used the following code snippet.
HOST = "pool.ntp.org"
PORT = 123
resolve = socket.getaddrinfo(HOST, PORT, socket.AF_INET, socket.SOCK_DGRAM)
addresses = []
for row in socket.getaddrinfo(HOST, PORT, socket.AF_INET, socket.SOCK_DGRAM):
addresses.append(row[4])
host, port = random.choice(addresses)
This just runs a DNS query, gets a bunch of NTP servers and picks one randomly.
The protocol itself is just sending a 48-byte packet and receiving a 48-byte packet in response. The packets are in the same format, you just send an empty packet and receive one that is filled in.