2023 10 05


Reading time: about 1 minute

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.

Citation

If you find this work useful, please cite it as:
@article{yaltirakli,
  title   = "2023 10 05",
  author  = "Yaltirakli, Gokberk",
  journal = "gkbrk.com",
  year    = "2024",
  url     = "https://www.gkbrk.com/journal/2023-10-05"
}
Not using BibTeX? Click here for more citation styles.
IEEE Citation
Gokberk Yaltirakli, "2023 10 05", December, 2024. [Online]. Available: https://www.gkbrk.com/journal/2023-10-05. [Accessed Dec. 27, 2024].
APA Style
Yaltirakli, G. (2024, December 27). 2023 10 05. https://www.gkbrk.com/journal/2023-10-05
Bluebook Style
Gokberk Yaltirakli, 2023 10 05, GKBRK.COM (Dec. 27, 2024), https://www.gkbrk.com/journal/2023-10-05

Comments

© 2024 Gokberk Yaltirakli