. 最近有个项目需要这个功能。网络上大部分找的一些对于年份获取的结果有错误。。不过还是从网络上得到了资料实现了功能。发出来给需要用到的人吧。。
注释的代码是初始化网络的代码,返回值st就获取到的网络时间了。
//从网络获取是否处于合法时间 EXPORT BOOL GetValidityTime() { ULONG ulTime = 0; SYSTEMTIME st; BOOL bRet = TRUE; //InitSocket(); if (GetNETTime(&ulTime) == TRUE) { st = UpTimer(ulTime); } else { bRet = FALSE; ::MessageBox(NULL, L"网络时间获取失败,请保证使用时网络通畅.", NULL, MB_OK); } return bRet; } //获取网络时间 BOOL GetNETTime(ULONG *ulData) { BOOL bRet = TRUE; SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { ::MessageBox(NULL, L"创建socket失败!\n", NULL, MB_OK); bRet = FALSE; goto _Exit; } sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(37); sin.sin_addr.S_un.S_addr = inet_addr("132.163.4.101"); if (connect(s,(sockaddr*)&sin,sizeof(sin)) == -1) { ::MessageBox(NULL, L"连接失败!\n", NULL, MB_OK); bRet = FALSE; goto _Exit; } ULONG ulTime = 0; int nLength = sizeof(sin); int nRecv = ::recv(s, (char*)&ulTime, sizeof(ulTime), 0); if (nRecv != 0 && nRecv != SOCKET_ERROR) { *ulData = ntohl(ulTime);//转换为从TCP / IP网络为u_long到主机字节顺序 } else { ::MessageBox(NULL, L"服务器不能确定当前时间!\n", NULL, MB_OK); bRet = FALSE; goto _Exit; } _Exit: if (s != INVALID_SOCKET) { ::closesocket(s); } return bRet; } #define HIGHTIME 21968699 // 21968708 // Jan 1, 1900 FILETIME.highTime #define LOWTIME 4259332096 // 1604626432 // Jan 1, 1900 FILETIME.lowtime SYSTEMTIME UpTimer(ULONG ulTime) { FILETIME ft = {0}; SYSTEMTIME st = {0}; st.wYear = 1900; st.wMonth = 1; st.wDay = 1; st.wMonth = 0; st.wMinute = 0; st.wSecond = 0; st.wMilliseconds = 0; UINT64 uiCurTime, uiBaseTime, uiResult; uiBaseTime = ((UINT64) HIGHTIME << 32) + LOWTIME; uiCurTime = (UINT64)ulTime * (UINT64)10000000; uiResult = uiBaseTime + uiCurTime; FileTimeToSystemTime((LPFILETIME)&uiResult, &st); return st; }
发表评论