Tuesday, November 18, 2008

RFC868 UDP Time Protocol Client

Here is an RFC 868 UDP Time Protocol Client implementation in less than 30 lines of python.
I know...just what you always wanted. It is a long story, but I needed a time protocol client (that would run on Windows) for testing a service we're developing at work. There are tons of implementations of the TCP version of the protocol, but I couldn't find a UDP implementation for Windows to save my life. Python to the rescue.
from socket import *
from struct import unpack
from time import ctime, sleep
from sys import argv

argv = argv[1:]
if len(argv) == 0:
argv = [ 'time-nw.nist.gov' ]

s = socket(AF_INET, SOCK_DGRAM)

for server in argv:
print server, ":",
s.sendto('', 0, (server, 37))
t = long(unpack('!L', s.recv(16)[:4])[0])
# Convert from 1900/01/01 epoch to 1970/01/01 epoch
t -= 2208988800
print ctime(t)
except timeout:
print "TIMEOUT"
print "ERROR"

In case you are curious, the sleep(2) at the end is there so our testers can simply click the icon on their desktop and have time to actually see the results before Windows closes the console window.

By default, it queries the time-nw.nist.gov server, but you can specify any number of servers to query on the command-line.

No comments: