Herhangi bir ekstra paket gerektirmeksizin uzak bir NTP sunucusundan zaman bilgisini çekmek için aşağıdaki gibi bir kod yazmanız yeterli olmaktadır.
Aşağıdaki örnekte ulakbim.gov.tr ntp2 sunucusundan zaman bilgisi çekilmektedir.
#!/usr/bin/env python from socket import AF_INET, SOCK_DGRAM import sys, socket import struct, time def getNTPTime(host = "ntp2.ulakbim.gov.tr"): port = 123 buf = 1024 address = (host,port) msg = '\x1b' + 47 * '\0' TIME1970 = 2208988800 # 1970-01-01 00:00:00 client = socket.socket( AF_INET, SOCK_DGRAM) client.sendto(msg.encode('utf-8'), address) msg, address = client.recvfrom( buf ) t = struct.unpack( "!12I", msg )[10] t -= TIME1970 return time.ctime(t).replace(" "," ") if __name__ == "__main__": print(getNTPTime())
Top comments (0)