ActiveState Code

Recipe 117211: Simple (very) SNTP client


Uses the SNTP protocol (as specified in RFC 2030) to contact the server specified in the command line and report the time as returned by that server. This is about the simplest (and dumbest) client I could manage.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from socket import *
import struct
import sys
import time

TIME1970 = 2208988800L      # Thanks to F.Lundh

client = socket( AF_INET, SOCK_DGRAM )
data = '\x1b' + 47 * '\0'
client.sendto( data, ( sys.argv[1], 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)

Discussion

I would like too see a more complete implementation of SNTP or even full-blown NTP in Python. Anyone interested? I might even try it myself.

Comments

  1. 1. At 2:27 p.m. on 27 jan 2003, Jeff Bauer said:

    from socket import *. Nice job in a few lines of code. I'd like to see the namespace-polluting import line replaced, especially in published Python code.

    replace: from socket import *
    with:    from socket import socket, AF_INET, SOCK_DGRAM
    
  2. 2. At 4:13 p.m. on 17 mar 2003, Simon Foster said:

    Done as requested. I can't login to change this code having lost my account details but the codes so short I can just post it here.

    import socket
    import struct
    import sys
    import time
    
    TIME1970 = 2208988800L      # Thanks to F.Lundh
    
    client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
    data = '\x1b' + 47 * '\0'
    client.sendto( data, ( sys.argv[1], 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)
    

Sign in to comment