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

Keith Thompson kst-u at mib.org
Tue Jul 25 10:52:43 UTC 2006


bg_ie at yahoo.com writes:
> Hi,
>
> 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;
>
> How might I calculate the fraction part?
>
> Thanks very much for your help,

First, "ntp.seconds" is a syntax error; identifiers can't contain '.'
characters.

I'm not familiar with NTP, but I think you're trying to get something
like the number of seconds since the year 1900.  You're assuming that
time() returns the number of seconds since 1970 -- which is commonly
true (and required by POSIX, I think), but not guaranteed by the C
standard.

The C standard itself guarantees only that time_t is an arithmetic
type capable of representing times.  It doesn't specify what the epoch
is, or even that there is an epoch, and it doesn't specify the
granularity.  There is no standard way to get a time precise to
fractions of a second.

Furthermore, even assuming a 1-second granularity and an epoch of
1970-01-01 00:00:00 GMT, your calculation:

    time(NULL) + 2208988800

will overflow a 32-bit signed long int.  For that matter, so will
2208988800 by itself (it exceeds 2**31-1).

If you can assume POSIX compliance, there's probably more you can do
-- but then you should probably be posting to comp.unix.programmer,
not comp.lang.c or comp.lang.c.moderated.

-- 
Keith Thompson (The_Other_Keith) kst-u at mib.org  <http://www.ghoti.net/~kst>
San Diego Supercomputer Center             <*>  <http://users.sdsc.edu/~kst>
We must do something.  This is something.  Therefore, we must do this.
-- 
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