日期:2014-05-16 浏览次数:20702 次
//ntp_rev.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/time.h> #include <netinet/in.h> #include <netdb.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/ioctl.h> #define int8 char #define uint8 unsigned char #define uint32 unsigned int #define ulong32 unsigned long #define long32 long #define int32 int #define long64 long long #define debug //3600s*24h*(365days*70years+17days) #define From00to70 0x83aa7e80U #define NTPSVR "192.168.2.8" //myserver #define NTPPORT 123 typedef struct NTPPACKET { uint8 li_vn_mode; uint8 stratum; uint8 poll; uint8 precision; //有符号整数表示本地时钟精确度 ulong32 root_delay; //到达服务器的一次往返的总延时,是15到16位有符号的定点小数 ulong32 root_dispersion; // 到达服务器的一次标准误差,是15-16位的无符号的定点小数 int8 ref_id[4]; ulong32 reftimestamphigh; //本地时钟最后被设定或校正的时间T4 ulong32 reftimestamplow; ulong32 oritimestamphigh; //向服务器请求分离客户机的时间戳,采用64位时标格式T1 ulong32 oritimestamplow; ulong32 recvtimestamphigh; //向服务器请求到客户机的时间戳,采用64位时标格式T2 ulong32 recvtimestamplow; ulong32 trantimestamphigh; //向客户机答复分离服务器的时间戳,采用64位时标格式T3,用T3来校正本地时间 ulong32 trantimestamplow; }NTPPacket; NTPPacket ntppack,newpack; //定义为long64,解决32位数的符号位问题 long64 firsttimestamp,finaltimestamp; long64 diftime,delaytime; void NTP_Init() { bzero(&ntppack,sizeof(ntppack)); ntppack.li_vn_mode=0x1b;//0|(3<<2)|(3<<5); //获取初始时间戳T1 firsttimestamp="From00to70"+time(NULL);//-8*3600; ntppack.oritimestamphigh=htonl(firsttimestamp); } int main() { // ulong32 clienttime; // ulong32 diftime,firsttimestamp,finaltimestamp; // fd_set inset1; int32 sockfd; struct timeval tv,tv1; struct timezone tz; struct sockaddr_in addr; addr.sin_family=AF_INET; //IPV4协议 addr.sin_port =htons(NTPPORT); //NTP专用的123端口 addr.sin_addr.s_addr=inet_addr(NTPSVR);//INADDR_ANY,NTPSVR; //校时服务器 bzero(&(addr.sin_zero),8); //清零 /*build a socket */ if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0) { perror("create socket error!\n"); exit(1); } /*bind a port*/ // int bDontLinger = 0; //setsockopt( socket, SOL_SOCKET, SO_DONTLINGER, ( const char* )&bDontLinger, sizeof( int ) ); // int bReuseaddr=1; // setsockopt(sockfd,SOL_SOCKET ,SO_REUSEADDR,(const char*)&bReuseaddr,sizeof(int)); /* if(bind(sockfd,(struct sockaddr *)&addr,sizeof(struct sockaddr))==-1) { perror("bind error"); exit(1); } */ while(1) { NTP_Init(); //发送数据请求包 // sendto(sockfd,&ntppack,sizeof(ntppack), // 0,(struct sockaddr *)&addr,sizeof(struct sockaddr)); // recvfrom(s,buffer,sizeof(buffer),0,&addr,&addr_len); // sendto(s,buffer,len,0,&addr,addr_len); int recvbyte=0; printf("sockfd %d \n",sockfd); recvbyte=recv(sockfd,&newpack,sizeof(newpack),0); //接收数据在newpack中。 printf("OK %d \n",recvbyte); // printf("OK\n"); if(recvbyte<0) { perror