timesync with python?

François Pinard pinard at iro.umontreal.ca
Tue Sep 14 21:05:52 EDT 1999


Holger Jannsen <holger at phoenix-edv.netzservice.de> wrote:

> But I also thought that someone has an idea about that before and did
> it likely better than me. So, do you know a weblink to a script which
> already nearly does what I need? Perhaps directly with interrogation at
> port 37 NTP?

"Fredrik Lundh" <fredrik at pythonware.com> writes:

> from the eff-bot archives:

> import socket, time
> HOST = "my.server"
> PORT = 37
> TIME1970 = 2208988800L # 1970-01-01 00:00:00
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect(HOST, PORT)
> b = s.recv(4)
> t0 = ord(b[3]) + (ord(b[2])<<8) + (ord(b[1])<<16) + (ord(b[0])<<24L)
> t1 = int(time.time()) + TIME1970
> dt = int(t0 - t1)
> print "delta is", dt, "seconds"

Isn't that fun?  I just coded this, a few days ago.  My formulation is
almost identical, yet a tiny bit cleaner, maybe:


import socket, struct, time

def time_delta(machine):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(machine, socket.getservbyname('time', 'tcp'))
    data = client.recv(4)
    client.close()
    remote_secs = int(struct.unpack('!I', data)[0] - 2208988800L)

    local_secs = int(time.time())
    return remote_secs - local_secs

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list