vc 获取网络时间


方式1 :

#include <WinSock2.h>
#include <Windows.h>
#pragma comment(lib, "WS2_32")  // 链á′接ó到μ?WS2_32.lib     
class CInitSock
{     
public:     
    CInitSock(BYTE minorVer = 2, BYTE majorVer = 2)     
    {     
        // 初3?始ê?化ˉWS2_32.dll     
        WSADATA wsaData;     
        WORD sockVersion = MAKEWORD(minorVer, majorVer);     
        if(::WSAStartup(sockVersion, &wsaData) != 0)     
        {     
            exit(0);     
        }     
    }     
    ~CInitSock()     
    {        
        ::WSACleanup();      
    }     
};
CInitSock initS;
BOOL NistGetTime(LPFILETIME OutTime)
{
    BOOL bOk;
    struct hostent *host;
    bOk = FALSE;
    if (host = gethostbyname("time.nist.gov"))
    {
        SOCKET s;
        in_addr ia;
        CHAR IpText[32];
        memcpy(&ia, host->h_addr, host->h_length);
        lstrcpyA(IpText, inet_ntoa(ia));
        s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        if (s != INVALID_SOCKET)
        {
            sockaddr_in sac;
            memset(&sac, 0, sizeof(sac));
            sac.sin_family = AF_INET;
            sac.sin_port = htons(37);
            sac.sin_addr.s_addr = inet_addr(IpText);
            if (connect(s, (sockaddr*)&sac, sizeof(sac)) == 0)
            {
                ULONG nTime;
                if (recv(s, (PCHAR)&nTime, sizeof(nTime), 0) == sizeof(nTime))
                {
                    LONGLONG llt;
                    nTime = ntohl(nTime);
                    llt = 0x014F373BFDE04000;//1900.1.1
                    llt += LONGLONG(nTime) * 10000000;
                    memcpy(OutTime, &llt, sizeof(FILETIME));
                    bOk = TRUE;
                }
            }
            closesocket(s);
        }
    }
    return bOk;
}
int _tmain(int argc, _TCHAR* argv[])
{
    FILETIME ft;
    CInitSock initS;
    NistGetTime(&ft);
    SYSTEMTIME st;
    FileTimeToSystemTime(&ft,&st);
    return 0;
}


方式2 mfc:

CTime NistGetTime()
{
//时间同步
CSocket sockClient;
TIME_ZONE_INFORMATION tzinfo;
DWORD dwStandardDaylight;
long bias,sminute,shour;
vector <string> vi;
string strServer;
BOOL ret;
//将时间服务器放在一个VECTOR中。
strServer = "time.nist.gov";
vi.push_back(strServer); 
strServer = "time-a.nist.gov";
vi.push_back(strServer); 
strServer = "time-b.nist.gov";
vi.push_back(strServer); 
strServer = "time-nw.nist.gov";
vi.push_back(strServer); 
strServer = "nist1.nyc.certifiedtime.com";
vi.push_back(strServer); 
strServer = "time-b.nist.gov";
vi.push_back(strServer); 

//初始化CSocket
AfxSocketInit();
sockClient.Create();   //创建socket


dwStandardDaylight = GetTimeZoneInformation(&tzinfo); //获取时区与UTC的时间差 应该返回-8
bias = tzinfo.Bias;
if (dwStandardDaylight == TIME_ZONE_ID_INVALID) //函数执行失败
{
return; 
}
if (dwStandardDaylight == TIME_ZONE_ID_STANDARD) //标准时间有效
bias += tzinfo.StandardBias;

if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT) //夏令时间
bias += tzinfo.DaylightBias;

shour = bias/60;
sminute = fmod((float)bias,60);

//循环判断服务器是否连接成功
for (int n=0; n < vi.size(); ++ n)
{
ret = sockClient.Connect(vi[n].c_str(),13);
if (1 == ret)
break;   

}

unsigned char nTime[100] = {0}; //临时接收数据要求足够的大

sockClient.Receive(nTime, sizeof(nTime)); //接收服务器发送来得的数据
sockClient.Close();    //关闭socket

CString strTime;
strTime.Format("%s",nTime);

int first=strTime.Find("-");
int second=strTime.Find("-",first+1);

int tfirst = strTime.Find(":");
int tsecond = strTime.Find(":",tfirst+1);


int hyear=2000+atoi(strTime.Mid(first-2,2));
int hmonth=atoi(strTime.Mid(first+1,2));
int hday=atoi(strTime.Mid(second+1,2));
int hhour=atoi(strTime.Mid(tfirst-2,2))-shour;
int hminute=atoi(strTime.Mid(tfirst+1,2))-sminute;
int hsecond=atoi(strTime.Mid(tsecond+1,2));
CTime temptime(hyear,hmonth,hday,hhour,hminute,hsecond);
return temptime;
}
上一篇:java 简单使用redis


下一篇:js笔记——js里var与变量提升