Create ntp timestamp with gettimeofday
I need to calculate the ntp timestamp using gettimeofday. Below is an example of how I did it with method comments. Looking good to you guys? (minus error checking). Also, here's the codepad .
#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 OR with the tv_usecs cast as a uin32_t, dropping the fractional
// part
ntp_time = ((tv_ntp << 32) | (uint32_t)tv_usecs);
}
a source to share
extern uint64_t tvtontp64(struct timeval *tv) {
uint64_t ntpts;
ntpts = (((uint64_t)tv->tv_sec + 2208988800u) << 32) + ((uint32_t)tv->tv_usec * 4294.967296);
return (ntpts);
}
I am using 4294.967296 not ... 5 since this relation to the total score of 0 needs to count 4294967296 ticks per second or 4294.967296 for each idle time to check this, since 1,000,000 usec will overflow [in seconds] the tick range should be from 0 to ( 1000000-1).
This is an oversimplification and suits my purpose. Unique IPv6 Unicast Local Addresses [RFC4193]
a source to share
No need to use uint64_t
here - unsigned long long
guaranteed to be at least 64 bits wide.
You also don't need to go to double
and double
, as it NTP_SCALE_FRAC * 1000000
will easily fit into unsigned long long
.
EPOCH
should be unsigned long long
, and not unsigned long
, so the addition with is tv.tv_sec
not wrapped.
All:
const unsigned long long EPOCH = 2208988800ULL;
const unsigned long long NTP_SCALE_FRAC = 4294967295ULL;
unsigned long long tv_to_ntp(struct timeval tv)
{
unsigned long long tv_ntp, tv_usecs;
tv_ntp = tv.tv_sec + EPOCH;
tv_usecs = (NTP_SCALE_FRAC * tv.tv_usec) / 1000000UL;
return (tv_ntp << 32) | tv_usecs;
}
a source to share