Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime, timedelta, timezone
- from socket import socket, getaddrinfo, AF_INET, SOCK_DGRAM
- from struct import unpack
- def ntp_date(host="pool.ntp.org"):
- NTP_QUERY = bytearray(48)
- NTP_QUERY[0] = 0x1B
- addr = getaddrinfo(host, 123)[0][-1]
- with socket(AF_INET, SOCK_DGRAM) as sock:
- sock.settimeout(1)
- res = sock.sendto(NTP_QUERY, addr)
- try:
- msg = sock.recv(48)
- except TimeoutError:
- return None
- date = unpack("!I", msg[40:44])[0]
- # NTPs EPOCH starts at 1900-01-01
- return datetime(1900, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=date)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement