#include <iostream.h> #include <winsock.h> #include <stdio.h> #pragma comment(lib, "ws2_32.lib") #define NET_TIME_PORT 37 #define TIMEOUT_CONNECT 5 #define TIMEOUT_RECEIVE 1 char* sever[] = { "129.132.2.21", "129.6.15.28", "129.6.15.29", "132.163.4.101", "132.163.4.102", "132.163.4.103", "128.138.140.44", "192.43.244.18", "131.107.1.10", "66.243.43.21", "216.200.93.8", "208.184.49.9", "207.126.98.204", "207.200.81.113", "205.188.185.33", NULL }; BOOL GetRemoteTime(char* szSever, unsigned long& ulTime) { SOCKET sock = socket(AF_INET, SOCK_STREAM, 0); //使用TCP协议 if(sock == INVALID_SOCKET) { return FALSE; } unsigned long flag = 1; if ((ioctlsocket(sock, FIONBIO, &flag) == 0)) { sockaddr_in severAddr; severAddr.sin_family = AF_INET; severAddr.sin_port = htons(NET_TIME_PORT); severAddr.sin_addr.S_un.S_addr = inet_addr(szSever); connect(sock, (sockaddr*)&severAddr, sizeof(severAddr)); struct fd_set mask; FD_ZERO(&mask); FD_SET(sock, &mask); struct timeval timeout; timeout.tv_sec = TIMEOUT_CONNECT; timeout.tv_usec = 0; if (select(0, NULL, &mask, NULL, &timeout) == 1) { timeout.tv_sec = TIMEOUT_RECEIVE; if (select(0, &mask, NULL, NULL, &timeout) == 1) { if (recv(sock, (char*)&ulTime, 4, 0) == 4) { ulTime = ntohl(ulTime); closesocket(sock); return TRUE; } } } } closesocket(sock); return FALSE; } void MySetTime(unsigned long ulTime) { FILETIME ft; SYSTEMTIME st; st.wYear = 1900; st.wMonth = 1; st.wDay = 1; st.wHour = 0; st.wMinute = 0; st.wSecond = 0; st.wMilliseconds = 0; SystemTimeToFileTime(&st, &ft); LARGE_INTEGER li = *(LARGE_INTEGER*)&ft; li.QuadPart += (LONGLONG)10000000 * ulTime; ft = *(FILETIME*)&li; FileTimeToSystemTime(&ft, &st); SetSystemTime(&st); } int main() { //初始化TCP协议 WSADATA wsaData; if(WSAStartup(MAKEWORD(2,2), &wsaData) != 0) { cout<<"初始化网络协议失败!"<<endl; return -1; } int i = 0; unsigned long ulTime = 0; while (sever[i] != NULL) { if (GetRemoteTime(sever[i], ulTime)) { MySetTime(ulTime); char buff[100]; sprintf(buff, "已成功与时间服务器/r/n%s/r/n的时间同步", sever[i]); cout<<buff<<endl; return 0; } i++; } cout<<"所有服务器均不能正常连接或超时!"<<endl; WSACleanup(); return 0; }