| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- #include "ntpclient.h"
-
- #define NTP_PORT 123
- #define NTP_PACKET_SIZE 48
-
- // 发送NTP请求
- static int sendNTPRequest(NTPClient* client) {
- client->ntp_packet[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (client)
- ssize_t sentBytes = sendto(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,
- (struct sockaddr *)&client->server_addr, sizeof(client->server_addr));
- if (sentBytes < 0) {
- perror("sendto failed");
- return -1;
- }
- return 0;
- }
-
- // 接收NTP响应
- static int receiveNTPResponse(NTPClient* client) {
- socklen_t len = sizeof(client->server_addr);
- ssize_t receivedBytes = recvfrom(client->sockfd, client->ntp_packet, NTP_PACKET_SIZE, 0,
- (struct sockaddr *)&client->server_addr, &len);
- if (receivedBytes < 0) {
- perror("recvfrom failed");
- return -1;
- }
- return 0;
- }
-
- // 解析NTP响应中的时间
- static time_t parseNTPResponse(const char* ntp_packet) {
- unsigned int sec_since_1900 = ntohl(((unsigned int *)ntp_packet)[10]);
- unsigned int frac_sec = ntohl(((unsigned int *)ntp_packet)[11]);
- double frac = frac_sec * 2.0e-32;
- return (time_t)(sec_since_1900 - 2208988800U) + (time_t)frac;
- }
-
- // 创建NTP客户端实例
- NTPClient* createNTPClient(const char* ntp_server, int port) {
- NTPClient* client = (NTPClient*)malloc(sizeof(NTPClient));
- if (!client) {
- perror("malloc failed");
- return NULL;
- }
-
- // 创建UDP套接字
- if ((client->sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
- perror("socket creation failed");
- free(client);
- return NULL;
- }
-
- // 设置NTP服务器地址
- memset(&client->server_addr, 0, sizeof(client->server_addr));
- client->server_addr.sin_family = AF_INET;
- client->server_addr.sin_port = htons(port);
- if (inet_aton(ntp_server, &client->server_addr.sin_addr) == 0) {
- fprintf(stderr, "Invalid address/Address not supported\n");
- close(client->sockfd);
- free(client);
- return NULL;
- }
-
- return client;
- }
-
- // 销毁NTP客户端实例
- void destroyNTPClient(NTPClient* client) {
- if (client) {
- close(client->sockfd);
- free(client);
- }
- }
-
- // 从NTP服务器获取当前时间
- int getCurrentTimeFromNTP(NTPClient* client, time_t* current_time) {
- if (sendNTPRequest(client) < 0) {
- return -1;
- }
-
- if (receiveNTPResponse(client) < 0) {
- return -1;
- }
-
- *current_time = parseNTPResponse(client->ntp_packet);
- return 0;
- }
-
-
- // 根据时间获取星期信息
- int getCurrentWeekday(time_t current_time,char *weekday) {
- struct tm * timeinfo;
- timeinfo = localtime(¤t_time);
- if (timeinfo == NULL) {
- return -1;
- }
-
- // 格式化星期几
- strftime(weekday, 20, "%A", timeinfo); // %A 代表完整的星期名,例如:Sunday
-
- return 0;
- }
|