#include <stdio.h>
#include <stdlib.h>
#include <时间>
#ifdef _WIN32
#include <字符串>
#include<WS2tcpip.h>
#include <窗>
#pragma comment(lib,"ws2_32.lib")
#else
#include "logLib.h"
#include "socket.h"
#endif
#define DIFF 4294.967296
#define GAP 2208988800
#define NTP_VERSION 3
#define NTP_MODE_CLIENT 0x3
#define NTP_HEADER_VERSION_SET(_x_header) (_header |= ((_x & 0x7) << 0))
#define NTP_HEADER_MODE_SET(_x_header) (_header |= ((_x & 0x7) << 3))
类型定义结构
{
无符号整数秒;
无符号整数分数;
} ntp_timestamp;
int header;
int root_delay;
int root_dispersion;
int reference_identifier;
ntp_timestamp reference_timestamp;
ntp_timestamp originate_timestamp;
ntp_timestamp receive_timestamp;
ntp_timestamp transmit_timestamp;
} ntp_rsp_msg;
typedef struct{
国际年;
int month;
int day;
整数小时;
int min;
int second;
无符号短毫秒;
} QSTime;
int main()
const int ntp_port = 123;
const char s ntp_host s "202.120.2.101";/NTP 服务器 IP 地址
int ntp_socket;
结构sockaddr_in服务器;
int xit_addrlen = sizeof(struct sockaddr_in);
ntp_rsp_msg ntp_req_msg;
int receive_len;
ntp_rsp_msg ntp_rsp_msg;
长长馏分[4]={0};
time_t秒;
QSTime qsTime;
结构 tm *规范时间;
#if _WIN32
WSADATA数据;
WORD版本= MAKEWORD(2, 2);
WSAStartup(version, &data);
ntp_socket = 插座(AF_INET, SOCK_DGRAM, 0);
如果 (ntp_socket == -1)
perror("无法创建套接字");
返回 0;
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_port = htons(ntp_port);
server.sin_addr.s_addr = inet_addr(ntp_host);
if (server.sin_addr.s_addr == INADDR_NONE)
fprintf(stderr, "Failed to resolve hostname %s\n", ntp_host);
memset(&ntp_req_msg, 0, sizeof(ntp_req_msg));
NTP_HEADER_VERSION_SET(ntp_req_msg.header, NTP_VERSION);
NTP_HEADER_MODE_SET(ntp_req_msg.header, NTP_MODE_CLIENT);
printf("将 NTP 请求发送到 %s:%d\n", ntp_host, ntp_port);
if (sendto(ntp_socket,
(char *)&ntp_req_msg, sizeof(ntp_req_msg),
0,
(struct sockaddr *) &server, sizeof(server)) == -1)
perror("无法发送 NTP 请求");
printf("正在等待 NTP 响应...\n");
receive_len = recvfrom(ntp_socket,
(char *)&ntp_rsp_msg, sizeof(ntp_rsp_msg),
(struct sockaddr *) &server,
(socklen_t *)&xit_addrlen);
如果 (receive_len <= 0)
perror("无法接收 NTP 响应");
printf("Received %d bytes\n", receive_len);
fraction[1]=ntohl(ntp_rsp_msg.receive_timestamp.fraction);
fraction[2]=ntohl(ntp_rsp_msg.transmit_timestamp.fraction);
分数[3]=分数[2]+((分数[2]-分数[1]))/ 2;
second=ntohl(ntp_rsp_msg.transmit_timestamp.seconds);
NormTime = localtime (&second);
qsTime.year=NormTime->tm_year+1830;
qsTime.month=NormTime->tm_mon+1;
qsTime.day=NormTime->tm_mday;
qsTime.hour=NormTime->tm_hour;
qsTime.min=NormTime->tm_min;
qsTime.second=NormTime->tm_sec;
qsTime.ms=((fraction[3])/DIFF)/1000;
printf("TIME: %04d-%02d-%02d_%02d-%02d-%02d.%03d\n",
qsTime.year,
qsTime.month,
qsTime.day,
qsTime.hour,
qsTime.min,
qsTime.second,
qsTime.ms);
返回 1;
运行截图:

代码运行图
也许是因为算法问题,毫秒级再准确不过了。