poll = Data(0) >> 8 & 0xff; prec = Data(0) & 0xff; if (prec & 0x80) prec|=0xffffff00; delay = Data(1); disp = Data(2); refid = Data(3); reftime.coarse = Data(4); reftime.fine = Data(5); orgtime.coarse = Data(6); orgtime.fine = Data(7); rectime.coarse = Data(8); rectime.fine = Data(9);*/ trantime.coarse = Data(10); trantime.fine = Data(11); printf(\ printf(\ printf(\ printf(\ new_time->tv_sec = trantime.coarse - JAN_1970; new_time->tv_usec = USEC(trantime.fine); //print just precise to second printf(\}
void set_local_time(struct timeval new_time) { /* need root user. */ if (0 != getuid() && 0 != geteuid()) { printf(\ return; } settimeofday(&new_time, NULL); }
int main(void) { int sockfd; struct sockaddr_in addr_src, addr_dst; fd_set fds_read; int ret; int receivebytes; unsigned int buf[12]; int addr_len; struct timeval timeout, new_time; struct ntptime udp_arrival_local_timestamp;
31
struct hostent* host;
addr_len = sizeof(struct sockaddr_in);
memset(&addr_src, 0, addr_len); addr_src.sin_family = AF_INET;
addr_src.sin_addr.s_addr = htonl(INADDR_ANY); addr_src.sin_port = htons(0);
memset(&addr_dst, 0, addr_len); addr_dst.sin_family = AF_INET;
host = gethostbyname(NTP_SERVER);
memcpy(&(addr_dst.sin_addr.s_addr), host->h_addr_list[0], 4); addr_dst.sin_port = htons(NTP_PORT);
/* create socket. */
if (-1 == (sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))) { printf(\ exit(1); }
/* bind local address. */
ret = bind(sockfd, (struct sockaddr*) &addr_src, addr_len); if (-1 == ret) { printf(\ close(sockfd); }
/* connect to ntp server. */
ret = connect(sockfd, (struct sockaddr*) &addr_dst, addr_len); if (-1 == ret) { printf(\ close(sockfd); }
/*get and set time*/ while (1) { FD_ZERO(&fds_read); FD_SET(sockfd, &fds_read); timeout.tv_sec = 6; timeout.tv_usec = 0;
ret = select(sockfd + 1, &fds_read, NULL, NULL, &timeout); if (0 == ret || !FD_ISSET(sockfd, &fds_read)) { /* send ntp protocol packet. */
send_packet(sockfd);
32
continue; }
/* recv ntp server's response. */
receivebytes = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *) &addr_dst, &addr_len); if (-1 == receivebytes) { printf(\ close(sockfd); exit(1); }
/* get local timestamp. */
//get_udp_arrival_local_timestamp(&udp_arrival_local_timestamp); /* get server's time and print it. */ get_new_time(buf, &new_time);
/* set local time to the server's time, if you're a root user. */ //set_local_time(new_time);
}
close(sockfd); return 0;
}
33