Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java NTP client

Tags:

java

ntp

I need my software to communicate with an NTP server to determine the local clock offset. I have tried using the org.apache.commons.net.ntp package, but its implementation is rather poor when running on Windows, because of the use of System.currentTimeMillis() to determine the time before and after the NTP packet exchange. As you may or may not know, this value is only updated when the system clock ticks, which on most modern Win2k3 servers is at 64Hz or every 15.625ms. This greatly limits the accuracy of the clock offset calculation.

Ntpd uses the CPU high-frequency timer to interpolate between system clock ticks, and achieve much higher resolution time. Do you know of a Java implementation that uses this or a similar technique? Or do you know of any other NTP implementation other than Apache's?

like image 263
Matt Howells Avatar asked May 29 '09 09:05

Matt Howells


4 Answers

there is a NTP Java implementation on support.ntp.org

like image 188
dfa Avatar answered Oct 05 '22 08:10

dfa


Since this question ranks very high on Google for "Java NTP client":

Android has a nice, compact Apache-licensed implementation of a Simple NTP client: android.net.SntpClient.

It would need to be modified to run on non-Android java, but this should be trivial, since the code is about 100 lines of code plus another 100 lines of detailed comments, with no external dependencies except the Android system clock - and by chance, it is ready to accept relative timers like nanoTime() since it already uses such a relative timer.

like image 25
Jan Schejbal Avatar answered Oct 05 '22 10:10

Jan Schejbal


I have written a java implementation (Java 7) that you can use: SntpClient

like image 31
user2179737 Avatar answered Oct 05 '22 10:10

user2179737


If you're using Java 5 or above, can you use System.nanoTime() to perform a more accurate measurement of time offsets ? You'd have to modify your existing NTP code, but you should have the source for it, and I wouldn't expect this to be difficult.

like image 42
Brian Agnew Avatar answered Oct 05 '22 09:10

Brian Agnew