c語言實現系統時間校正工具代碼分享_C 語言

來源:互聯網
上載者:User

複製代碼 代碼如下:

//*******************************************************************
//Time Protocol是一種非常簡單的應用程式層協議。它返回一個未格式化的32位位元字,
 //這個數字描述了從1900年1月1日午夜到現在的秒數。伺服器在連接埠37監聽協議請求,以
 //TCP/IP或者UDP/IP格式返迴響應。將伺服器的傳回值轉化為本地時間是用戶端程式的責任。
 //這裡使用的時間伺服器是129.132.2.21,更多的伺服器位址在“http://tf.nist.gov/service/time-servers.html
 //網站列出。
 //*******************************************************************

#include<iostream>
#include<WinSock2.h>

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<<"socketerror:"<<GetLastError()<<endl;
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<<"connecterror:"<<WSAGetLastError()<<endl;
return0;
}

//等待接收時間協議返回,最好使用非同步IO,以便設定逾時
ULONGulTime=0;
intiRecv=recv(s,(char*)&ulTime,sizeof(ulTime),0);
if(iRecv>0)
{
ulTime=ntohl(ulTime);
SetTimeFromTP(ulTime);
cout<<"成功與伺服器時間同步!"<<endl;
}
else
{
cout<<"時間伺服器不能確定目前時間!"<<endl;
}

shutdown(s,SD_RECEIVE);
closesocket(s);

WSACleanup();
return0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.