1

I am currently writing an NTP client and server in Java. I am calculating the offset and round trip delay using the NTP timestamps. I should point out that i am calculating these for the seconds (first 32 bits) and the fractions (second 32 bits) separately. I am getting offset results such as 0 seconds and 1859395165 fractions.

My question is how can I use these offsets to print out what my system time would be if it was adjusted according to the given offset?

I was thinking that I could just add the fractions onto the fractions part of a timestamp for my systems current time, but if the sum of the fractions were greater than 1 second I believe I would encounter problems as my seconds would then be incorrect.

toffoo
  • 11
  • 3
  • FYI: http://stackoverflow.com/questions/925191/java-ntp-client – assylias Apr 01 '15 at 16:27
  • I'm not too clear what problem youre trying to solve, but it *sounds* like you are worried about integer overflows? Why not simply put the seconds and fraction into a long (long = (((long) seconds) << 32) | (fraction & 0xFFFFFFFFL)), calulate the difference and then split them again? – Durandal Apr 01 '15 at 17:39
  • Thanks for your reply. Im just trying to print what my system time should be when the offset has been applied. – toffoo Apr 01 '15 at 17:55

1 Answers1

0

You could convert the fraction to milliseconds first and then do the calculations. Then lets say you get the time 11:05:21:900 back from the server and the offset was 200 ms. Then you just add that to 11:05:21:900 and get 11:05:22:100.

You just need a function that checks if you hit a new second/minute/etc after adding the offset. The start of that code could look like this.

systemMs += offsetMs;
if (systemMs >= 1000)
{
    systemS += 1;
    systemMS -= 1000;
    if (systemS >= 60)
    {
        etc
    }
}
Jesper Evertsson
  • 613
  • 9
  • 28