C++ set the system time and system time network update methods

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

This article illustrates the method of C++ setting system time and updating system time network. Share with you for your reference. The specific implementation method is as follows:

//Set the system time 
based on the time returned void setTimeFromTP(ULONG ulTime)

    FILETIME ft; 
    SYSTEMTIME st; 
 
    //Convert base time to Windows file time & NBSP; < br / >     st.wYear = 1900; 
    st.wMonth = 1; 
    st.wDay = 1; 
    st.wHour = 0; 
    st.wMinute = 0; 
    st.wSecond = 0; 
    st.wMilliseconds = 0; 
 
    SystemTimeToFileTime(&st, &ft); 
 
    LONGLONG* pLLong = (LONGLONG*)&ft; 
    *pLLong += (LONGLONG)10000000*ulTime; 
    FileTimeToSystemTime(&ft, &st); 
    ::SetSystemTime(&st); 

 
void main() 

    CInitSock initSock; 
    SOCKET s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 
    if (s == INVALID_SOCKET) 
    { 
        printf("socket error..."); 
        return; 
    } 
    sockaddr_in servAddr = {0}; 
    servAddr.sin_family = AF_INET; 
    servAddr.sin_port = ::htons(37); 
    servAddr.sin_addr.S_un.S_addr = ::inet_addr("69.25.96.13"); //Don't use the 210.72.145.44 IP, this is the usual TMD return value in heaven & PI; < br / >     if (SOCKET_ERROR == ::connect(s, (sockaddr*)&servAddr, sizeof(servAddr))) 
    { 
        printf("connect error.."); 
        return; 
    } 
 
    //Receiving time & NBSP; < br / >     ULONG ulTime = 0; 
    int nRecv = ::recv(s, (char*)&ulTime, sizeof(ulTime), 0); 
    if (nRecv > 0)  //Receiving data & NBSP; < br / >     { 
        ulTime = ::ntohl(ulTime); 
        setTimeFromTP(ulTime); 
    } 
    else 
    { 
        printf("recv error..."); 
        return; 
    } 
     
    ::closesocket(s); 
    printf("*******************************"); 
    getchar(); 
}

Hope that the article described in the C++ programming to help you.


Related articles: