c++获取网络时间
test.h
#pragma once #include <winsock2.h> #include <ws2tcpip.h> #include<ctime> #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #pragma comment (lib,"Ws2_32.lib") struct NTPPacket { union { struct _ControlWord { unsigned int uLI : 2; // 00 = no leap, clock ok unsigned int uVersion : 3; // version 3 or version 4 unsigned int uMode : 3; // 3 for client, 4 for server, etc. unsigned int uStratum : 8; // 0 is unspecified, 1 for primary reference system, // 2 for next level, etc. int nPoll : 8; // seconds as the nearest power of 2 int nPrecision : 8; // seconds to the nearest power of 2 }; int nControlWord; // 4 }; int nRootDelay; // 4 int nRootDispersion; // 4 int nReferenceIdentifier; // 4 __int64 n64ReferenceTimestamp; // 8 __int64 n64OriginateTimestamp; // 8 __int64 n64ReceiveTimestamp; // 8 int nTransmitTimestampSeconds; // 4 int nTransmitTimestampFractions; // 4 };
.cpp
#include <iostream> #include <string> #include <atlstr.h> #include <vector> #include <io.h> #include <stdlib.h> #include <iostream> #pragma warning(disable:4996) #define JAN_1970 0x83aa7e80 /* 1900年~1970年之间的时间秒数 */ using namespace std; #include"test.h"//包含上面的头文件,文件名自取 int Get_time_t(time_t & ttime) { ttime = 0; WSADATA wsaData; // Initialize Winsock int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData); if (iResult != 0) return 1; int result, count; int sockfd = 0, rc; sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0) return 2; fd_set pending_data; timeval block_time; NTPPacket ntpSend = { 0 }; ntpSend.nControlWord = 0x1B; NTPPacket ntpRecv; SOCKADDR_IN addr_server; addr_server.sin_family = AF_INET; addr_server.sin_port = htons(123);//NTP服务默认为123端口号 addr_server.sin_addr.S_un.S_addr = inet_addr("120.25.115.20"); //该地址为阿里云NTP服务器的公网地址,其他NTP服务器地址可自行百度搜索。 SOCKADDR_IN sock; int len = sizeof(sock); if ((result = sendto(sockfd, (const char*)&ntpSend, sizeof(NTPPacket), 0, (SOCKADDR *)&addr_server, sizeof(SOCKADDR))) < 0) { int err = WSAGetLastError(); return 3; } FD_ZERO(&pending_data); FD_SET(sockfd, &pending_data); //timeout 10 sec block_time.tv_sec = 10; block_time.tv_usec = 0; if (select(sockfd + 1, &pending_data, NULL, NULL, &block_time) > 0) { //获取的时间为1900年1月1日到现在的秒数 if ((count = recvfrom(sockfd, (char*)&ntpRecv, sizeof(NTPPacket), 0, (SOCKADDR*)&sock, &len)) > 0) ttime = ntohl(ntpRecv.nTransmitTimestampSeconds) - JAN_1970; } closesocket(sockfd); WSACleanup(); return 0; } int main() { //获取到的t为一个时间戳,请根据需求转换成可视化时间 time_t rawtime; int filecode = Get_time_t(rawtime); if (filecode == 0) { char cTimePARTNUMBER[256] = ""; struct tm * timeinfo; //time(&rawtime); timeinfo = localtime(&rawtime); char buffer1[256]; strftime(cTimePARTNUMBER, sizeof(buffer1), "%Y%m%d-%H:%M:%S", timeinfo); string strTimePARTNUMBER = ""; strTimePARTNUMBER = cTimePARTNUMBER; cout << strTimePARTNUMBER << endl; } else { cout << filecode << endl; } cin.get(); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异