//*******************************************************************
//Time Protocol是一種非常簡單的應用層協議。它返回一個未格式化的32位二進制數字,
//這個數字描述了從1900年1月1日午夜到現在的秒數。服務器在端口37監聽協議請求,以
//TCP/IP或者UDP/IP格式返回響應。將服務器的返回值轉化為本地時間是客戶端程序的責任。
//這里使用的時間服務器是129.132.2.21,更多的服務器地址在“http://tf.nist.gov/service/time-servers.html
//網站列出。
//*******************************************************************
#include
#include
usingnamespacestd;
#pragmacomment(lib,"ws2_32")
voidSetTimeFromTP(ULONGulTime)
{
//Windows文件時間是一個64位的值,它是從1601年1月1日中午12:00到現在的時間間隔,
//單位是1/10000000秒,即1000萬分之1秒
FILETIMEft;
SYSTEMTIMEst;
st.wYear=1900;
st.wMonth=1;
st.wDay=1;
st.wHour=0;
st.wMinute=0;
st.wSecond=0;
st.wMilliseconds=0;
SystemTimeToFileTime(&st,&ft);
//然后將TimeProtocol使用的基準時間加上已經逝去的時間,即ulTime
LONGLONG*pllLong=(PLONGLONG)&ft;
//注意文件時間單位是1/10000000秒,即1000萬分之1秒
*pllLong+=(LONGLONG)10000000*ulTime;
//再將時間轉化回來,更新系統時間
FileTimeToSystemTime(&ft,&st);
SetSystemTime(&st);
}
intmain(intargc,char**argv)
{
WSADATAwsaData;
WSAStartup(WINSOCK_VERSION,&wsaData);
SOCKETs=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(INVALID_SOCKET==s)
{
cout<
return0;
}
SOCKADDR_INservAddr;
servAddr.sin_family=AF_INET;
servAddr.sin_port=htons(37);
servAddr.sin_addr.S_un.S_addr=inet_addr("129.132.2.21");
if(-1==connect(s,(PSOCKADDR)&servAddr,sizeof(servAddr)))
{
cout<
return0;
}
//等待接收時間協議返回,最好使用異步IO,以便設置超時
ULONGulTime=0;
intiRecv=recv(s,(char*)&ulTime,sizeof(ulTime),0);
if(iRecv>0)
{
ulTime=ntohl(ulTime);
SetTimeFromTP(ulTime);
cout<
}
else
{
cout<
}
shutdown(s,SD_RECEIVE);
closesocket(s);
WSACleanup();
return0;
}