[Cpp] // /// // NetTime. cpp file # include ".. /common/InitSock. h "# include <stdio. h> CInitSock initSock; void SetTimeFromTP (ULONG ulTime) // set the system time according to the time returned by the time Protocol {// Windows file time is a 64-bit value, it is the time interval from noon on January 1, January 1, 1601 to the present. // The unit is 1/1000 0000 seconds, that is, 1 second of 10 million minutes (100-nanosecond) FILETIME ft; SYSTEMTIME st; // first, convert the benchmark time (January 1, 1900 00:00:00 0 ms) to the Windows file time st. wyear= 1900; st. WMonth = 1; st. wDay = 1; st. wHour = 0; st. wMinute = 0; st. wSecond = 0; st. wMilliseconds = 0; SystemTimeToFileTime (& st, & ft); // Add the reference Time used by the Time Protocol and the elapsed Time, that is, ulTime LONGLONG * pLLong = (LONGLONG *) & ft; // note that the file time unit is 1/1000 0000 seconds, that is, 1 second (10 million-nanosecond) * pLLong + = (LONGLONG) 100 * ulTime; // convert the time back and update the system time FileTimeToSystemTime (& ft, & st); SetSystemTime (& st) ;}int main () {SOCKET s =: so Cket (AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s = INVALID_SOCKET) {printf ("Failed socket () \ n"); return 0 ;}// enter the remote address information, connect to the time server sockaddr_in servAddr; servAddr. sin_family = AF_INET; servAddr. sin_port = htons (37); // The time server used here is 129.132.2.21. For more information, see http://tf.nist.gov/service/its.htm servAddr. sin_addr.S_un.S_addr = inet_addr ("129.132.2.21"); if (: connect (s, (sockaddr *) & servAddr, sizeof (servAddr) = =-1) {printf ("Failed connect () \ n"); return 0 ;}// wait for the time that the Protocol returns. After learning the Winsock I/O model, it is best to use asynchronous I/O to set the timeout ULONG ulTime = 0; www.2cto.com int nRecv =: recv (s, (char *) & ulTime, sizeof (ulTime), 0); if (nRecv> 0) {ulTime = ntohl (ulTime); SetTimeFromTP (ulTime); printf ("time synchronization between success and time server! \ N ");} else {printf (" the time server cannot determine the current time! \ N ") ;}:: closesocket (s); return 0 ;}