#include <iostream> #include <stdio.h> #include "InitSock.h" using namespace std; void SetTimeFromTP(ULONG ulTime); int main(void) { CInitSock initSock; //创建套接字 SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { cout << "Failed socke()" << endl; return 0; } //创建套接字之后如果首先sendto可以不绑定 //若首先recvfrom则需要绑定 //填写远程地址信息 sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(37); addr.sin_addr.S_un.S_addr = inet_addr("129.6.15.28 "); //可在http://tf.nist.gov/service/time-servers.html得到IP //连接服务器 if (connect(s, (sockaddr*)&addr, sizeof(addr)) == -1) { cout << "Failed connect()" << endl; return 0; } //等待接收时间协议返回的时间,学习Winsock I/O模型后最好使用异步I/O ULONG ulTime = 0; int nRecv = recv(s, (char*)&ulTime, sizeof(ulTime), 0); if (nRecv > 0) { ulTime = ntohl(ulTime); SetTimeFromTP(ulTime); cout << "成功与服务器时间同步" << endl; cout << "接收到的数据: " << ulTime << endl; } else { cout << "服务器不能确认当前时间" << endl; } closesocket(s); getchar(); return 0; } void SetTimeFromTP(ULONG ulTime) { //Windows文件时间是一个64位的值,是从1601年1月1日中午12:00到现在的时间间隔 //单位是1/1000 0000秒即1000万分之1秒(100-nanosecond) FILETIME ft; SYSTEMTIME st; //首先将基准时间(1900.1.1.0.0.0.0)转换为windows文件时间 st.wYear = 1900; st.wMonth = 1; st.wDay = 1; st.wHour = 0; st.wMinute = 0; st.wSecond = 0; st.wMilliseconds = 0; SystemTimeToFileTime(&st, &ft); //然后将Time Protocol使用基准时间加上已经逝去的时间即ulTime LONGLONG *pLLong = (LONGLONG*)&ft; //注意文件时间的单位 *pLLong += (LONGLONG)10000000 * ulTime; //再将时间转换回来,更新系统时间 FileTimeToSystemTime(&ft, &st); //SetSystemTime(&st); cout << st.wYear << "年" << st.wMonth << "月" << st.wDay << "日" << st.wHour + 8<< "时" //... << st.wMinute << "分" << st.wSecond << "秒" << endl; }
原文地址:https://www.cnblogs.com/chenxingyang/p/9748123.html
时间: 2024-10-14 14:47:19