1BOOL UpdateSysTime()
2{
3 WORD wVersionRequested;
4 WSADATA wsaData;
5
6 // 初始化版本
7 wVersionRequested = MAKEWORD( 1, 1 );
8 if (0!=WSAStartup(wVersionRequested, &wsaData))
9 {
10 WSACleanup();
11 return FALSE;
12 }
13 if (LOBYTE(wsaData.wVersion)!=1 || HIBYTE(wsaData.wVersion)!=1)
14 {
15 WSACleanup( );
16 return FALSE;
17 }
18
19 // 这个IP是中国大陆时间同步服务器地址,可自行修改
20 SOCKET soc=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
21 struct sockaddr_in addrSrv;
22 addrSrv.sin_addr.S_un.S_addr=inet_addr("210.72.145.44");
23 addrSrv.sin_family=AF_INET;
24 addrSrv.sin_port=htons(123);
25
26 NTP_Packet NTP_Send,NTP_Recv;
27 NTP_Send.Control_Word = htonl(0x0B000000);
28 NTP_Send.root_delay = 0;
29 NTP_Send.root_dispersion = 0;
30 NTP_Send.reference_identifier = 0;
31 NTP_Send.reference_timestamp = 0;
32 NTP_Send.originate_timestamp = 0;
33 NTP_Send.receive_timestamp = 0;
34 NTP_Send.transmit_timestamp_seconds = 0;
35 NTP_Send.transmit_timestamp_fractions = 0;
36
37 if(SOCKET_ERROR==sendto(soc,(const char*)&NTP_Send,sizeof(NTP_Send),
38 0,(struct sockaddr*)&addrSrv,sizeof(addrSrv)))
39 {
40 closesocket(soc);
41 return FALSE;
42 }
43 int sockaddr_Size =sizeof(addrSrv);
44 if(SOCKET_ERROR==recvfrom(soc,(char*)&NTP_Recv,sizeof(NTP_Recv),
45 0,(struct sockaddr*)&addrSrv,&sockaddr_Size))
46 {
47 closesocket(soc);
48 return FALSE;
49 }
50 closesocket(soc);
51 WSACleanup();
52
53 SYSTEMTIME newtime;
54 float Splitseconds;
55 struct tm *lpLocalTime;
56 time_t ntp_time;
57
58 // 获取时间服务器的时间
59 ntp_time = ntohl(NTP_Recv.transmit_timestamp_seconds)-2208988800;
60 lpLocalTime = localtime(&ntp_time);
61 if(lpLocalTime == NULL)
62 {
63 return FALSE;
64 }
65
66 // 获取新的时间
67 newtime.wYear =lpLocalTime->tm_year+1900;
68 newtime.wMonth =lpLocalTime->tm_mon+1;
69 newtime.wDayOfWeek =lpLocalTime->tm_wday;
70 newtime.wDay =lpLocalTime->tm_mday;
71 newtime.wHour =lpLocalTime->tm_hour;
72 newtime.wMinute =lpLocalTime->tm_min;
73 newtime.wSecond =lpLocalTime->tm_sec;
74
75 // 设置时间精度
76 Splitseconds=(float)ntohl(NTP_Recv.transmit_timestamp_fractions);
77 Splitseconds=(float)0.000000000200 * Splitseconds;
78 Splitseconds=(float)1000.0 * Splitseconds;
79 newtime.wMilliseconds = (unsigned short)Splitseconds;
80
81 // 修改本机系统时间
82 SetLocalTime(&newtime);
83 return TRUE;
84}
posted on 2010-06-16 18:09
漂漂 阅读(4113)
评论(6) 编辑 收藏 引用 所属分类:
深入vc++