/************************************************************************/
/* 从时间服务器读取时间 */
/************************************************************************/
DWORD GetTimeFromServer(in_addr ipaddr)
{
DWORD dwRet = -1;
SOCKET sSock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sin;
if (sSock != INVALID_SOCKET)
{
memcpy(&sin.sin_addr, &ipaddr, sizeof(in_addr));
sin.sin_family = AF_INET;
sin.sin_port = htons(IPPORT_TIMESERVER);
//连接服务端
connect(sSock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in));
for (iRead = 0; iRead < 4; iRead += iResult)
{
/*读取时间信息*/
iResult = recv(sSock, (char*)&dwRet + iRead, 4 - iRead, 0);
if (iResult < 1)
{
break;
}
}
if (iRead == 4)
{
dwRet = ntohl(dwRet);
}
else
{
::MessageBox(NULL, "Getting time failed!", "Error", MB_OK | MB_ICONERROR);
}
closesocket(sSock);
}
return dwRet;
}
-----------------------------------------------------------------------------------------
WSADATA WSAData;
/*初始化套接字库*/
if (WSAStartup(MAKEWORD(2, 2), &WSAData) != 0)
{
MessageBox("WSAStartup failed.
");
WSACleanup();
return ;
}
in_addr timeServer = {128,138,140,44}; // 时间服务器IP地址
/*取服务器时间*/
DWORD dwTime = GetTimeFromServer(timeServer);
if (dwTime != -1) // 读取时间失败
{
UINT64 uiCurTime, uiBaseTime, uiResult;
SYSTEMTIME st;
uiBaseTime = ((UINT64) HIGHTIME << 32) + LOWTIME;
uiCurTime = (UINT64)dwTime * (UINT64)10000000;
uiResult = uiBaseTime + uiCurTime;
FileTimeToSystemTime((LPFILETIME)&uiResult, &st);
CString str = "";
str.Format("%d-%d-%d", st.wYear, st.wMonth, st.wDay); // 日期
AfxMessageBox(str);
}
else
{
MessageBox("获取时间失败");
}
WSACleanup();