I wrote a TCP Client to contact two NIST servers and get the difference between both the times. I have created two sockets for contacting both the servers, then using unixepoch, converted them to system time. While I expected thousands of seconds as difference in output, I am getting the difference as 0 or a few seconds. I couldn't figure out error in my code even after working on it whole day.
char *host = "129.6.15.29"; /* Maryland NIST server */
char *host1="216.228.192.69"; /*Oregon NIST server*/
char *service = "time"; /* default service name */
time_t now1,now2; /* 32-bit integer to hold time */
int s1,s2, n1,n2; /* socket descriptor, read count*/
double diff_t;
switch (argc) {
case 1:
host = "129.6.15.29";
host1="216.228.192.69";
break;
case 4:
service = argv[3];
case 3:
host = argv[1];
host1= argv[2];
break;
default:
fprintf(stderr, "usage: TCPTime [host [port]]\n");
exit(1);
}
s1 = connectTCP(host, service);
s2= connectTCP1(host1,service);
(void) write(s1, MSG, strlen(MSG));
(void) write(s2,MSG, strlen(MSG));
/* Read the time */
n1 = read(s1, (char *)&now1, sizeof(now1));
n2 = read(s2, (char *)&now2, sizeof(now2));
if (n1 < 0|| n2<0 )
errexit("read failed: %s\n", strerror(errno));
now1 = ntohl((unsigned long)now1); /* put in host order */
now1 -= UNIXEPOCH; /* convert UCT to UNIX epoch */
now2 = ntohl((unsigned long)now2); /* put in host order */
now2 -= UNIXEPOCH; /* convert UCT to UNIX epoch */
printf("%s", ctime(&now1));
printf("%s", ctime(&now2));
diff_t=difftime(now1,now2);
printf("difference between times:%f",diff_t);
exit(0);
Please let me know if my approach is right. Thanks for taking time to analyze and answer my question.
Here is the sample output:
Fri Oct 7 19:34:59 2016
Fri Oct 7 19:34:58 2016
difference between times:1.000000
In the time protocol (which you appear to be using), the server returns the number of seconds since January 1, 1900, midnight UTC (not midnight local time or any other time zone). Note that this measures from a specific moment, and the amount of time that has passed since then is the same regardless of what timezone you're in. Thus, the servers will return (almost) the same values at the same time regardless of what timezones they are in.