//*******************************************************************
//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 for protocol requests on port 37 to
//TCP/IP or UDP/IP format returns the response. It is the responsibility of the client program to convert the return value of the server to local time.
//The time server used here is 129.132.2.21, and more server addresses are in "/service/
//Site list.
//*******************************************************************
#include<iostream>
#include<>
usingnamespacestd;
#pragmacomment(lib,"ws2_32")
voidSetTimeFromTP(ULONGulTime)
{
//Windows file time is a 64-bit value, which is the time interval from 12:00 noon on January 1, 1601 to the present time.
//The unit is 1/1000000 seconds, that is, 1 second of 10 million
FILETIMEft;
SYSTEMTIMEst;
=1900;
=1;
=1;
=0;
=0;
=0;
=0;
SystemTimeToFileTime(&st,&ft);
//Then add the base time used by TimeProtocol to the elapsed time, i.e. ulTime
LONGLONG*pllLong=(PLONGLONG)&ft;
//Note that the file time unit is 1/1000000 seconds, that is, 1 second of 10 million
*pllLong+=(LONGLONG)10000000*ulTime;
//Convert the time back to 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;
}
//Waiting for the reception time protocol to return, it is best to use asynchronous IO to set the timeout
ULONGulTime=0;
intiRecv=recv(s,(char*)&ulTime,sizeof(ulTime),0);
if(iRecv>0)
{
ulTime=ntohl(ulTime);
SetTimeFromTP(ulTime);
cout<<"Successfully synchronized with server time!"<<endl;
}
else
{
cout<<"The time server cannot determine the current time!"<<endl;
}
shutdown(s,SD_RECEIVE);
closesocket(s);
WSACleanup();
return0;
}