Unlike the previous recipe, sometimes, you don't need to get the precise time from the NTP server. You can use a simpler version of NTP called simple network time protocol.
Writing an SNTP client
How to do it...
Let us create a plain SNTP client without using any third-party library.
Let us first define two constants: NTP_SERVER and TIME1970. NTP_SERVER is the server address to which our client will connect, and TIME1970 is the reference time on January 1, 1970 (also called Epoch). You may find the value of the Epoch time or convert to the Epoch time at http://www.epochconverter.com/. The actual client creates a UDP socket (SOCK_DGRAM) to connect to the server following the UDP protocol. The client then needs to send the SNTP protocol data ('\x1b' + 47 * '\0') in a packet. Our UDP client sends and receives data using the sendto() and recvfrom() methods.
When the server returns the time information in a packed array, the client needs a specialized struct module to unpack the data. The only interesting data is located in the 11th element of the array. Finally, we need to subtract the reference value, TIME1970, from the unpacked value to get the actual current time.
Listing 1.12 shows how to write an SNTP client as follows:
#!/usr/bin/env python # Python Network Programming Cookbook,
Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12
and Python 3.5.2. # It may run on any other version with/without
modifications. import socket import struct import sys import time NTP_SERVER = "0.uk.pool.ntp.org" TIME1970 = 2208988800 def sntp_client(): client = socket.socket( socket.AF_INET,
socket.SOCK_DGRAM ) data = '\x1b' + 47 * '\0' client.sendto( data.encode('utf-8'),
( NTP_SERVER, 123 )) data, address = client.recvfrom( 1024 ) if data: print ('Response received
from:', address) t = struct.unpack( '!12I', data )[10] t -= TIME1970 print ('\tTime=%s' % time.ctime(t)) if __name__ == '__main__': sntp_client()
This recipe prints the current time from the internet time server received with the SNTP protocol as follows:
$ python 1_12_sntp_client.py ('Response received from:',
('192.146.137.13', 123)) Time=Sat Jun 3 14:45:45 2017
How it works...
This SNTP client creates a socket connection and sends the protocol data. After receiving the response from the NTP server (in this case, 0.uk.pool.ntp.org), it unpacks the data with struct. Finally, it subtracts the reference time, which is January 1, 1970, and prints the time using the ctime() built-in method in the Python time module.