Create ntp time stamp from gettimeofday

Posted by krunk on Stack Overflow See other posts from Stack Overflow or by krunk
Published on 2010-04-15T00:27:56Z Indexed on 2010/04/15 0:33 UTC
Read the original article Hit count: 539

Filed under:
|
|
|
|

I need to calculate an ntp time stamp using gettimeofday. Below is how I've done it with comments on method. Look good to you guys? (minus error checking). Also, here's a codepad link.

#include <unistd.h>
#include <sys/time.h>

const unsigned long EPOCH = 2208988800UL; // delta between epoch time and ntp time
const double NTP_SCALE_FRAC = 4294967295.0; // maximum value of the ntp fractional part

int main()
{
  struct timeval tv;
  uint64_t ntp_time;
  uint64_t tv_ntp;
  double tv_usecs;

  gettimeofday(&tv, NULL);
  tv_ntp = tv.tv_sec + EPOCH;

  // convert tv_usec to a fraction of a second
  // next, we multiply this fraction times the NTP_SCALE_FRAC, which represents
  // the maximum value of the fraction until it rolls over to one. Thus,
  // .05 seconds is represented in NTP as (.05 * NTP_SCALE_FRAC)
  tv_usecs = (tv.tv_usec * 1e-6) * NTP_SCALE_FRAC;

  // next we take the tv_ntp seconds value and shift it 32 bits to the left. This puts the 
  // seconds in the proper location for NTP time stamps. I recognize this method has an 
  // overflow hazard if used after around the year 2106
  // Next we do a bitwise AND with the tv_usecs cast as a uin32_t, dropping the fractional
  // part
  ntp_time = ((tv_ntp << 32) & (uint32_t)tv_usecs);
}

© Stack Overflow or respective owner

Related posts about c++

Related posts about c