<wbr></wbr>
//////////////////////////////////////////////////////////
// NetTime.cpp文件
//通过internet从129.132.2.21中获取时间信息
#include "../common/InitSock.h"
#include <stdio.h>
CInitSock initSock;<wbr></wbr>
void SetTimeFromTP(ULONG ulTime)<wbr>//根据时间协议返回的时间设置系统时间<br>{<br><wbr>//Windows文件时间是一个64位的值,它是从1601年1月1日中午12:00到现在的时间间隔,<br><wbr>// 单位是1/1000 0000秒,即1000万分之1秒(100-nanosecond)<br><wbr>FILETIME ft;<br><wbr>SYSTEMTIME st;</wbr></wbr></wbr></wbr></wbr>
<wbr>//首先将基准时间(1900年1月1日0点0分0秒0毫秒)转化为Windows文件时间<wbr><br><wbr>st.wYear = 1900;<br><wbr>st.wMonth = 1;<br><wbr>st.wDay = 1;<br><wbr>st.wHour = 0;<br><wbr>st.wMinute = 0;<br><wbr>st.wSecond = 0;<br><wbr>st.wMilliseconds = 0;<br><wbr>SystemTimeToFileTime(&st,&ft);</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
<wbr>// 然后将TimeProtocol使用的基准时间加上以及逝去的时间,即ulTime<br><wbr>LONGLONG *pLLong = (LONGLONG*)&ft;<br><wbr>// 注意,文件时间单位是1/10000000秒,即1000万分之1秒(100-nanosecond )<br><wbr>*pLLong += (LONGLONG)10000000 * ulTime;</wbr></wbr></wbr></wbr>
<wbr>// 再将时间转化回来,更新系统时间<br><wbr>FileTimeToSystemTime(&ft,&st);<wbr><br><wbr>SetSystemTime(&st);<br>}</wbr></wbr></wbr></wbr>
int main()
{
<wbr>SOCKET s = ::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);<br><wbr>if(s == INVALID_SOCKET)<br><wbr>{<br><wbr><wbr>printf(" Failed socket()\n");<br><wbr><wbr>return 0;<br><wbr>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>
<wbr>// 填写远程地址信息,连接到时间服务器<br><wbr>sockaddr_in servAddr;<br><wbr>servAddr.sin_family = AF_INET;<br><wbr>servAddr.sin_port = htons(37);<br><wbr>//这里使用的时间服务器是129.132.2.21,更多地址请参考http://tf.nist.gov/service/its.htm<br><wbr>servAddr.sin_addr.S_un.S_addr =inet_addr("129.132.2.21");<br><wbr>if(::connect(s,(sockaddr*)&servAddr, sizeof(servAddr)) ==-1)<br><wbr>{<br><wbr><wbr>printf(" Failed connect()\n");<br><wbr><wbr>return 0;<br><wbr>}<br><wbr><br><wbr>// 等待接收时间协议返回的时间。学习了WinsockI/O模型之后,最好使用异步I/O,以便设置超时<br><wbr>ULONG ulTime = 0;<br><wbr>int nRecv = ::recv(s,(char*)&ulTime, sizeof(ulTime), 0);<br><wbr>if(nRecv > 0)<br><wbr>{<br><wbr><wbr>ulTime = ntohl(ulTime);<br><wbr><wbr>SetTimeFromTP(ulTime);<br><wbr><wbr>printf("成功与时间服务器的时间同步!\n");<br><wbr>}<br><wbr>else<br><wbr>{<br><wbr><wbr>printf("时间服务器不能确定当前时间!\n");<br><wbr>}<br><wbr><br><wbr>::closesocket(s);<br><wbr>return 0;<br>}</wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr></wbr>