Current code
def time():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1B
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(timeout)
s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
finally:
s.close()
val = struct.unpack("!I", msg[40:44])[0]
Proposal
msg, src = s.recvfrom(48)
# Right host AND a full 48-byte reply. Skip spoofed/runt packets
if src[0] == addr[0] and len(msg) >= 48:
# got the response
else:
# not from the right host or packet too short
# that may break on -> val = struct.unpack("!I", msg[40:44])[0]
Current code
Proposal