网络时间核对

来源:互联网 发布:幸福蓝海网络学 编辑:程序博客网 时间:2024/05/20 20:18
#include <WinSock2.h>#include <Windows.h>#include <stdio.h>#pragma comment (lib,"ws2_32.lib")void SetFromTime(ULONG nlong){FILETIME ft;SYSTEMTIME st;ZeroMemory(&st,sizeof(st));st.wYear=1900;st.wMonth=1;st.wDay=1;SystemTimeToFileTime(&st,&ft);LONGLONG *pLong=(LONGLONG*)&ft;*pLong+=(LONGLONG)10000000*nlong;FileTimeToSystemTime(&ft,&st);SetSystemTime(&st);return ;}int main (void){WSADATA wsaData;WSAStartup(MAKEWORD(2,2),&wsaData);SOCKET sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if (sock==INVALID_SOCKET)return false;sockaddr_in sin;sin.sin_family=AF_INET;sin.sin_port=htons(37);sin.sin_addr.S_un.S_addr=inet_addr("128.138.141.172");//time.nist.govif (connect(sock,(SOCKADDR*)&sin,sizeof(sin))==SOCKET_ERROR){printf("连接失败\n");return false;}ULONG ulTime=0;if (recv(sock,(TCHAR*)&ulTime,sizeof(ulTime),0)==SOCKET_ERROR){printf("接收失败\n");return false;}ULONG nlong=ntohl(ulTime);SetFromTime(nlong);printf("时间核对成功\n");WSACleanup();return 0;}

0 0
原创粉丝点击