I've written a ntp client in python to query a time server and display the time and the program executes but does not give me any results. I'm using python's 2.7.3 integrated development environment and my OS is Windows 7. Here is the code:
# File: Ntpclient.py
from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time
# # Set the socket parameters
host = "pool.ntp.org"
port = 123
buf = 1024
address = (host,port)
msg = 'time'
# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00
# connect to server
client = socket.socket( AF_INET, SOCK_DGRAM)
client.sendto(msg, address)
msg, address = client.recvfrom( buf )
t = struct.unpack( "!12I", data )[10]
t -= TIME1970
print "\tTime=%s" % time.ctime(t)
Advertisements. The most widely used protocol for synchronizing time and which has been widely accepted as a practice is done through Network Time Protocol (NTP).
The NTP client enables the appliance or virtual machine to synchronize its internal clock with an NTP server on your network or on the internet. You can also configure the NTP client through the UI, see Performing time synchronization.
Use ntplib:
The following should work on both Python 2 and 3:
import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))
Output:
Fri Jul 28 01:30:53 2017
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With