how validate NTP time synchronization

user1316216 picture user1316216 · Apr 5, 2012 · Viewed 11.3k times · Source

I need create an application that validates NTP time synchronization on each machine. In other words, I need to determine if each machine is my LAN is synched to a common time server (stratum). So, far I came up with two ways.

1) Have the NTP client on each machine generate the statistics file. If I take this approach, which one of the statistics file should I examine to determine if the time on the machine is within some tolerance of the time server? There is a peerstats, clockstats and loopstats. Do any of those files contain information which I can use to determine if the time is synced up?

2) Invoke the ntpq command line argument and pipe its output. Parse the output.

Right now I prefer option 1, but, as I indicated, I am not sure if any of the NTP statistics file contain information which I can use to determine if time is synchronized.

Is there a better approach.

Is there an API which I can use to query the NTP client directly?

Thanks for your help.

Answer

dtoux picture dtoux · Mar 7, 2013

You could run ntpq -c "rv 0 stratum,offset" command and parse the output. If returned stratum is <16 then offset will be the time difference between the ntp pool and you system clock in milliseconds.

There is a also libntpq library in development. It is in early betas, but if you need something badly enough it should be usable.

Update 2016-10-07: It looks like libntpq project is long time defunct but a library with identical name is included with ntp source. It looks useable but it most likely will need to be linked statically. One should be able to tolerate GPL in order to use it in this manner.