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;
}