DEV Community

Cover image for NTP sunucusundan zaman bilgisi çekebilme
Ali Orhun Akkirman for Açıklab

Posted on

NTP sunucusundan zaman bilgisi çekebilme

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()) 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)