#!/usr/bin/env python3
import sys
import time
import struct
from socket import socket, AF_INET, SOCK_DGRAM
from contextlib import closing
NTP_QUERY = b'\x1b' + 47 * b'\0'
NTP_DELTA = 86400 * (70 * 365 + 17) # seconds from 1900 to 1970
NTP_PACKET_FORMAT = '!12I'
def ntp_time(host="pool.ntp.org", port=123):
with closing(socket(AF_INET, SOCK_DGRAM)) as client:
client.sendto(NTP_QUERY, (host, port))
response, address = client.recvfrom(1024)
if response:
unpacked = struct.unpack(NTP_PACKET_FORMAT,
response[0:struct.calcsize(NTP_PACKET_FORMAT)])
return unpacked[10] + float(unpacked[11]) / 2 ** 32 - NTP_DELTA
if __name__ == '__main__':
try:
sys.argv[1]
except IndexError:
pass
print(time.ctime(ntp_time()))