simple SNTP python script
Question: I need help to complete following script:

    
    
    import socket
    import struct
    import sys
    import time
    
    NTP_SERVER = '0.uk.pool.ntp.org'
    TIME1970 = 2208988800L
    
    def sntp_client():
        client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        data = str.encode('\xlb' + 47 * '\0')
        client.sendto(data, (NTP_SERVER, 123))
        data, addr = client.recvfrom(1024)
        if data:
            print('Response received from:', addr)
        t = struct.unpack('!12I', data)[10]
        t -= TIME1970
        print('\tTime: %s' % time.ctime(t))
    
    if __name__ == '__main__':
        sntp_client()
    

Expected output:

    
    
    Response received from: ('80.82.244.120', 123)
          Time: Tue Sep 13 14:49:38 2016
    

Problem is that program is not giving any output. It looks like it stucks at:

    
    
    data, addr = client.recvfrom(1024)
    

I hope someone can help me with this.


Answer: There is nothing wrong with your script as written, you need to look for
another reason why the server might not be responding to you, such as firewall
settings. My own python SNTP script is almost exactly the same:

    
    
    #!/bin/env python
    
    import socket
    import struct
    import sys
    import time
    
    TIME1970 = 2208988800L      # Thanks to F.Lundh
    
    pow2_31 = pow(2,31)
    pow2_32 = pow(2,32)
    pow2_16 = pow(2,16)
    
    if len(sys.argv) < 2:
        sys.stderr.write("Usage : " + sys.argv[0] + " <SNTP server>")
        exit(1)
    
    server = sys.argv[1]
    
    client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
    data = '\x1b' + 47 * '\0'
    time_start = time.time()
    try:
        client.sendto( data, ( server, 123 ))
        client.settimeout(2)
    except:
        print "server <%s> not recognized" % (server)
        exit(2)
    try:
        data, address = client.recvfrom( 1024 )
    except socket.timeout:
        print "timed out"
        exit(3)
    
    if data:
        time_reply = (time.time() - time_start) * 1000
        print 'received %d bytes  from %s in %d ms :' % (len(data), address, time_reply)
        upacket = struct.unpack( '!48B', data )
        print upacket
    

usage: $ ./sntp_client.py 0.uk.pool.ntp.org

received 48 bytes from ('83.170.75.28', 123) in 154 ms : (28, 3, 3, 236, 0, 0,
1, 171, 0, 0, 3, 0, 20, 139, 208, 232, 219, 177, 86, 148, 230, 192, 1, 15, 0,
0, 0, 0, 0, 0, 0, 0, 219, 177, 88, 27, 60, 214, 85, 212, 219, 177, 88, 27, 60,
238, 157, 39)

