Winsock編程基繼承基礎(網絡對時程序)

 

#include <iostream>
#include <stdio.h>

#include "InitSock.h"

using namespace std;

void SetTimeFromTP(ULONG ulTime);

int main(void)
{
    CInitSock initSock;
    //建立套接字
    SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET)
    {
        cout << "Failed socke()" << endl;
        return 0;
    }
    //建立套接字以後若是首先sendto能夠不綁定
    //若首先recvfrom則須要綁定

    //填寫遠程地址信息
    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(37);
    addr.sin_addr.S_un.S_addr = inet_addr("129.6.15.28 "); //可在http://tf.nist.gov/service/time-servers.html獲得IP

    //鏈接服務器
    if (connect(s, (sockaddr*)&addr, sizeof(addr)) == -1)
    {
        cout << "Failed connect()" << endl;
        return 0;
    }

    //等待接收時間協議返回的時間,學習Winsock I/O模型後最好使用異步I/O
    ULONG ulTime = 0;
    int nRecv = recv(s, (char*)&ulTime, sizeof(ulTime), 0);
    if (nRecv > 0)
    {
        ulTime = ntohl(ulTime);
        SetTimeFromTP(ulTime);
        cout << "成功與服務器時間同步" << endl;
        cout << "接收到的數據: " << ulTime << endl;
    }
    else
    {
        cout << "服務器不能確認當前時間" << endl;
    }
    
    closesocket(s);
    
    getchar();
    return 0;
}

void SetTimeFromTP(ULONG ulTime)
{
    //Windows文件時間是一個64位的值,是從1601年1月1日中午12:00到如今的時間間隔
    //單位是1/1000 0000秒即1000萬分之1秒(100-nanosecond)
    FILETIME ft;
    SYSTEMTIME st;
    //首先將基準時間(1900.1.1.0.0.0.0)轉換爲windows文件時間
    st.wYear = 1900;
    st.wMonth = 1;
    st.wDay = 1;
    st.wHour = 0;
    st.wMinute = 0;
    st.wSecond = 0;
    st.wMilliseconds = 0;

    SystemTimeToFileTime(&st, &ft);
    //而後將Time Protocol使用基準時間加上已經逝去的時間即ulTime
    LONGLONG *pLLong = (LONGLONG*)&ft;
    //注意文件時間的單位
    *pLLong += (LONGLONG)10000000 * ulTime;
    //再將時間轉換回來,更新系統時間
    FileTimeToSystemTime(&ft, &st);
    //SetSystemTime(&st);
    cout << st.wYear << ""
        << st.wMonth << ""
        << st.wDay << ""
        << st.wHour + 8<< ""    //...    
        << st.wMinute << ""
        << st.wSecond << "" << endl;
        
}
相關文章
相關標籤/搜索