网络时间协议 --- 网络对时程序

 1 // TCPIP time protocol.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5  #include <winsock2.h>
 6  #include <stdio.h>
 7  #pragma comment(lib,"WS2_32")
 8  class CInitSock
 9  {
10  public:
11      CInitSock(BYTE minorVer=2,BYTE majorVer=2)
12      {
13          WSADATA wsaData;
14          WORD sockVersion = MAKEWORD(minorVer,majorVer);
15          if(::WSAStartup(sockVersion,&wsaData)!=0)
16          {
17              exit(0);
18          }
19      }
20      ~CInitSock()
21      {
22          ::WSACleanup();
23      }
24  };
25 CInitSock initSock;
26 void SetTimeFromTP(ULONG ulTime)
27 {
28     FILETIME ft;
29     SYSTEMTIME st;
30     st.wYear = 1900;
31     st.wMonth = 1;
32     st.wDay = 1;
33     st.wHour = 0;
34     st.wMinute = 0;
35     st.wSecond = 0;
36     st.wMilliseconds = 0;
37     SystemTimeToFileTime(&st,&ft);
38 
39     LONGLONG *pLLong=(LONGLONG*)&ft;
40     *pLLong +=(LONGLONG)10000000*ulTime;
41     FileTimeToSystemTime(&ft,&st);
42     SetSystemTime(&st);
43 }
44 int main()
45 {
46     SOCKET s = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
47     if(s == INVALID_SOCKET)
48     {
49         printf("Failed socket()\n");
50         return 0;
51     }
52     sockaddr_in servAddr;
53     servAddr.sin_family = AF_INET;
54     servAddr.sin_port = htons(37);
55 
56     servAddr.sin_addr.S_un.S_addr = inet_addr("18.145.0.30");
57     if(::connect(s,(sockaddr*)&servAddr,sizeof(servAddr)) == -1)
58     {
59         printf("Failed connect()\n");
60         return 0;
61     }
62 
63     ULONG ulTime = 0;
64     int nRecv = ::recv(s,(char*)&ulTime,sizeof(ulTime),0);
65     if(nRecv>0)
66     {
67         ulTime=ntohl(ulTime);
68         SetTimeFromTP(ulTime);
69         printf("成功与时间服务器的时间同步!\n");
70     }
71     else
72     {
73         printf("时间服务器不能确定当前时间!\n");
74     }
75     ::closesocket(s);
76     return 0;
77 }

试了好多服务器IP地址,都不好使.....郁闷....

你可能感兴趣的:(时间)