# ------------------------------------------------------------
# Copyright © 2026/2027 Dr. Mohammad Alja'afreh. All rights reserved.
# PSUT IoT Engineering Learning Platform
# ------------------------------------------------------------
import socket, struct, time
 
# ---- Real public time servers: NTP uses UDP port 123.
NTP_SERVER = ('pool.ntp.org', 123)
# 48-byte request; first byte 0x1b = version 3, client mode.
packet = b'\x1b' + 47 * b'\0'
 
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
    s.settimeout(3)                  # give up after 3 s (UDP may lose it)
    s.sendto(packet, NTP_SERVER)     # one datagram out ...
    data, addr = s.recvfrom(48)      # ... one datagram back
 
# Bytes 40-43 hold the server time in seconds since 1900.
secs_1900 = struct.unpack('!I', data[40:44])[0]
# Subtract 70 years of seconds to get Unix time (since 1970).
unix_time = secs_1900 - 2208988800
print('Answer from', addr)
utc = time.gmtime(unix_time)
print('UTC time:', time.strftime('%Y-%m-%d %H:%M:%S', utc))
