[ntp:questions] Re: Calculating NTP timestamp in C program

Richard Bos rlb at hoekstra-uitgeverij.nl
Tue Jul 25 10:53:14 UTC 2006


bg_ie at yahoo.com wrote:

> I wish to write a C program which obtains the system time and hence
> uses this time to print out its ntp equivalent.
> 
> Am I right in saying that the following is correct for the seconds part
> of the ntp time?
> 
> long int ntp.seconds = time(NULL) + 2208988800;

Not at all. It _may_ be correct for some (perhaps quite common)
implementations, but it's not reliably so. time() returns _a_
representation of the system time. Which representation is used is
implementation-dependent. (Oh, and of course you can't declare a single
struct member like that. Assign to it, yes; but you have to declare the
struct as a whole.)
If you want the number of seconds since a particular moment, the best
you can do is this:

  struct tm then_struct;
  time_t then;
  long seconds;

  then_struct.tm_year= <the year of your base date>;
  /* ...and so on until... */
  then_struct.tm_sec = <the seconds of your base time>;
  then=mktime(&then_struct);

  seconds=difftime(time(), then);

It may be, btw, that your first time cannot fit in a time_t at all; for
example, on many common systems the NTP start time will be before the
earliest representable time, albeit not much before. Not much is, alas,
enough in this case. (To be less circumlocutory, the epoch under POSIX
is 00:00:00 on 1970-01-01; time_t, on such systems, is a signed long
int; and if that system is 32-bits and uses 32-bit longs, as many do,
2**15 seconds is just over 68 years, making the most negative time_t
represent a time somewhere in 1901... just over a year after NTP's
1900-01-01 :-/ ).
In such cases, the easy solution is to use a later start time, compute
the difference in seconds between that time and now, and then add the
(fixed, and known in advance) number of seconds between the helper start
time and the real start time. And then add a comment explaining why that
number of seconds was chosen, please...

> How might I calculate the fraction part?

You can't, in ISO C. On some systems, a time_t _might_ be a long int
representing hundreths of a second since foo. On others, it might be a
double representing seconds, with fractional part, since bar. On many,
it has no fractional part at all, and whole seconds are all you have.
You'll have to resort to system-specific functions. Most systems have
some high resolution time function, for varying meanings of "high".

Richard
-- 
comp.lang.c.moderated - moderation address: clcm at plethora.net -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line.  Sorry.




More information about the questions mailing list