//*******************************************************************
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 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. Converting the server's return value to local time is the responsibility of the client program.
The time server used here is 129.132.2.21, with more server addresses in "http://tf.nist.gov/service/time-servers.html
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 to the present time of January 1, 1601,
Unit is 1/10 million seconds, that is 10 million 1 seconds
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 base time used by the Timeprotocol is then added to the elapsed time, i.e. Ultime
Longlong*plllong= (Plonglong) &ft;
Note that the file time Unit is 1/10 million seconds, or 10 million, 1 seconds.
*plllong+= (Longlong) 10000000*ultime;
Then turn back the time 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;
}
Wait for the receive time protocol to return, preferably using asynchronous IO to set timeouts
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<< "Time server cannot determine the current time!" "<<endl;
}
Shutdown (s,sd_receive);
Closesocket (s);
WSACleanup ();
Return0;
}