How can I access NTP clock in java

Mohammad Roohitavaf picture Mohammad Roohitavaf · Aug 2, 2016 · Viewed 11.3k times · Source

I have a distributed program written in java. I want my nodes access a synchronized physical clock.

I know NTP is a protocol for physical clock synchronization. I know that I can install it on linux by sudo apt-get ntp.

My question is when I install it, how can I access this synchronized clock in my java program? I mean what happens when I install ntp on my machine? my system clock will be sync?

Thanks :)

Answer

JasonM1 picture JasonM1 · Sep 3, 2016

If want to access NTP info in Java you can create UDP packet conforming to the NTP packet format (NTP RFC-1305) setting mode field to MODE_CLIENT (3) then send packet to NTP server port 123 and listen for a response.

The Apache Commons Net library already has the framework to do this using only a few lines of code.

 NTPUDPClient client = new NTPUDPClient();
 client.open();
 InetAddress hostAddr = InetAddress.getByName("*insert-target-server-host-name.com*");
 TimeInfo info = client.getTime(hostAddr);
 info.computeDetails(); // compute offset/delay if not already done
 Long offsetValue = info.getOffset();
 Long delayValue = info.getDelay();
 String delay = (delayValue == null) ? "N/A" : delayValue.toString();
 String offset = (offsetValue == null) ? "N/A" : offsetValue.toString();

 System.out.println(" Roundtrip delay(ms)=" + delay
                + ", clock offset(ms)=" + offset); // offset in ms
 client.close();

Note that the local clock offset (or time drift) is calculated with respect to the local clock and the NTP server's clock according to this standard NTP equation.

LocalClockOffset = ((ReceiveTimestamp - OriginateTimestamp) +
                             (TransmitTimestamp - DestinationTimestamp)) / 2

Where OriginateTimestamp is the local time the client sent the packet (t1), ReceiveTimestamp is time request received by NTP server (t2), TransmitTimestamp is time reply sent by server (t3), and DestinationTimestamp is time at which reply received by client on local machine (t4).

See client example for full code:
https://commons.apache.org/proper/commons-net/examples/ntp/NTPClient.java