C language to achieve system time correction tool code sharing

  • 2020-04-02 02:08:49
  • OfStack


//*******************************************************************
//Time Protocol is a very simple application layer Protocol. It returns an unformatted 32-bit binary number,
 //This number describes the number of seconds from midnight on January 1, 1900 to the present. The server listens on port 37 for protocol requests to
 //The response is returned in TCP/IP or UDP/IP format. It is the responsibility of the client program to convert the return value of the server to the local time.
 //The time server used here is 129.132.2.21. More server addresses are available at "HTTP: s /s
 //Websites listed.
 //*******************************************************************

#include<iostream>
#include<WinSock2.h>
usingnamespacestd;
#pragmacomment(lib,"ws2_32")
voidSetTimeFromTP(ULONGulTime)
{
//Windows file time is a 64-bit value, which is the interval from 12:00 noon on January 1, 1601, to the present time,
//The units are 1/10 millionth of a second, which is 1/10 millionth of a second
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);
//The baseline time used by the TimeProtocol is then added to the time that has passed, namely ulTime
LONGLONG*pllLong=(PLONGLONG)&ft;
// Note file time The units are 1/10 millionth of a second, which is 1/10 millionth of a second
*pllLong+=(LONGLONG)10000000*ulTime;
//Convert the time back and update the system time
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;
}
//Wait for the receive time protocol to return, preferably using asynchronous IO to set a timeout
ULONGulTime=0;
intiRecv=recv(s,(char*)&ulTime,sizeof(ulTime),0);
if(iRecv>0)
{
ulTime=ntohl(ulTime);
SetTimeFromTP(ulTime);
cout<<" Successfully synchronize with server time !"<<endl;
}
else
{
cout<<" The time server cannot determine the current time! "<<endl;
}
shutdown(s,SD_RECEIVE);
closesocket(s);
WSACleanup();
return0;
}


Related articles: