ntpclient.c 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. #define _GNU_SOURCE
  2. #include <netdb.h>
  3. #include <signal.h>
  4. #include <unistd.h>
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include "ntpclient.h"
  8. #include "thread.h"
  9. #include "sys/time.h"
  10. #define NTP_PORT 123
  11. #define NTP_PACKET_SIZE 48
  12. // 发送NTP请求
  13. static int sendNTPRequest(NTPClient* client) {
  14. client->ntp_packet[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (client)
  15. ssize_t sentBytes = sendto(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,
  16. &client->server_addr, sizeof(client->server_addr));
  17. if (sentBytes < 0) {
  18. perror("sendto failed");
  19. return -1;
  20. }
  21. return 0;
  22. }
  23. // 接收NTP响应
  24. static int receiveNTPResponse(NTPClient* client) {
  25. socklen_t len = sizeof(client->server_addr);
  26. ssize_t receivedBytes = recvfrom(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,
  27. &client->server_addr, &len);
  28. if (receivedBytes < 0) {
  29. perror("recvfrom failed");
  30. return -1;
  31. }
  32. return 0;
  33. }
  34. // 解析NTP响应中的时间
  35. static time_t parseNTPResponse(const char* ntp_packet) {
  36. unsigned int sec_since_1900 = ntohl(((unsigned int *)ntp_packet)[10]);
  37. unsigned int frac_sec = ntohl(((unsigned int *)ntp_packet)[11]);
  38. double frac = frac_sec * 2.0e-32;
  39. return (time_t)(sec_since_1900 - 2208988800U) + (time_t)frac;
  40. }
  41. typedef struct {
  42. char ip[64];
  43. uint16_t port;
  44. }ipaddr_t;
  45. static int get_addr(ipaddr_t *addr, struct addrinfo *info)
  46. {
  47. addr->ip[0] = 0; addr->port = 0;
  48. if(info->ai_family==AF_INET) {
  49. struct sockaddr_in* p=(struct sockaddr_in*)(info->ai_addr);
  50. addr->port = htons(p->sin_port);
  51. inet_ntop(p->sin_family, &p->sin_addr, addr->ip, sizeof(addr->ip));
  52. }
  53. else if(info->ai_family==AF_INET6) {
  54. struct sockaddr_in6* p=(struct sockaddr_in6*)(info->ai_addr);
  55. addr->port = htons(p->sin6_port);
  56. inet_ntop(p->sin6_family, &p->sin6_addr, addr->ip, sizeof(addr->ip));
  57. }
  58. else {
  59. return -1;
  60. }
  61. return 0;
  62. }
  63. static void *tmp_thread(void *arg)
  64. {
  65. ipaddr_t ipa;
  66. int r,fd=-1,err;
  67. struct addrinfo hints;
  68. struct addrinfo *rp;
  69. NTPClient *pc=(NTPClient*)arg;
  70. char tmp[32];
  71. memset(&hints, 0, sizeof hints);
  72. hints.ai_family = AF_UNSPEC;
  73. hints.ai_socktype = SOCK_DGRAM;
  74. hints.ai_protocol = 0;//IPPROTO_UDP;
  75. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  76. pthread_testcancel();
  77. sprintf(tmp, "%d", pc->port);
  78. printf("___getaddrinfo in\n");
  79. err = getaddrinfo(pc->server, tmp, &hints, &pc->res);
  80. if(err){
  81. printf("___getaddrinfo from %s failed, %s\n", pc->server, gai_strerror(err));
  82. pthread_exit(NULL);
  83. }
  84. printf("___getaddrinfo out\n");
  85. for(rp=pc->res; rp; rp=rp->ai_next){
  86. get_addr(&ipa, rp);
  87. printf("socket to %s:%d ", ipa.ip, ipa.port);
  88. fd = socket(rp->ai_family, rp->ai_socktype, 0);
  89. if (fd>=0) {
  90. pc->sockfd = fd;
  91. pc->server_addr = *rp->ai_addr;
  92. printf("ok!\n");
  93. break;
  94. }
  95. printf("failed!\n");
  96. }
  97. if(fd>=0) {
  98. pc->flag = 1;
  99. }
  100. else {
  101. pc->flag = -1;
  102. }
  103. pthread_exit(NULL);
  104. }
  105. NTPClient* createNTPClient(const char* ntp_server, int port, int timeout_sec) {
  106. NTPClient* client = (NTPClient*)malloc(sizeof(NTPClient));
  107. if (!client) {
  108. perror("createNTPClient, malloc failed\n");
  109. return NULL;
  110. }
  111. pthread_t tid;
  112. client->server = (char*)ntp_server;
  113. client->port = port;
  114. client->res = NULL;
  115. client->flag = 0;
  116. pthread_create(&tid, NULL, tmp_thread, client);
  117. for(int i=0; i<timeout_sec; i++) {
  118. if(client->flag) {
  119. break;
  120. }
  121. sleep(1);
  122. }
  123. if(client->flag!=1) {
  124. if(client->flag==0) {
  125. printf("___getaddrinfo timeout, cancel thread %lu\n", (unsigned long)tid);
  126. pthread_cancel(tid);//SIGTERM
  127. pthread_join(tid, NULL);
  128. printf("___cancel ok!\n");
  129. }
  130. if(client->res) freeaddrinfo(client->res);
  131. free(client); return NULL;
  132. }
  133. if(client->res) freeaddrinfo(client->res);
  134. struct timeval tv;
  135. tv.tv_sec = timeout_sec;
  136. tv.tv_usec = 0;
  137. setsockopt(client->sockfd, SOL_SOCKET, SO_RCVTIMEO, (const void*)&tv, sizeof(tv));
  138. printf("___createNTPClient ok!\n");
  139. return client;
  140. }
  141. // 销毁NTP客户端实例
  142. void destroyNTPClient(NTPClient* client) {
  143. if (client) {
  144. close(client->sockfd);
  145. free(client);
  146. }
  147. }
  148. // 从NTP服务器获取当前时间
  149. int getCurrentTimeFromNTP(NTPClient* client, time_t* current_time) {
  150. if (sendNTPRequest(client) < 0) {
  151. return -1;
  152. }
  153. if (receiveNTPResponse(client) < 0) {
  154. return -1;
  155. }
  156. *current_time = parseNTPResponse(client->ntp_packet);
  157. return 0;
  158. }
  159. // 根据时间获取星期信息
  160. int getCurrentWeekday(time_t current_time,char *weekday) {
  161. struct tm * timeinfo;
  162. timeinfo = localtime(&current_time);
  163. if (timeinfo == NULL) {
  164. return -1;
  165. }
  166. // 格式化星期几
  167. strftime(weekday, 20, "%A", timeinfo); // %A 代表完整的星期名,例如:Sunday
  168. return 0;
  169. }