0

谁能举个例子从互联网上获取日期/时间,到目前为止我只使用 NetRemoteTOD 函数找到了信息。

但关键是我不知道如何使用它,服务器名称是什么。我刚刚在我的函数中尝试了以下代码,但它给出了运行时错误。

感谢帮助

LPTIME_OF_DAY_INFO pBuf = NULL;
NET_API_STATUS nStatus;
LPTSTR pszServerName = NULL;
int CurrentYear ;
int CurrentMonth ;
int CurrentDay ;
int CurrentHour;
int CurrentMin;

pszServerName = (LPTSTR) "time.windows.com";
//
// Call the NetRemoteTOD function.
//
nStatus = NetRemoteTOD((LPCWSTR) pszServerName,(LPBYTE *)&pBuf);
//
// If the function succeeds, display the current date and time.
//
if (nStatus == NERR_Success)
{
    if (pBuf != NULL)
    {

        CurrentYear =  pBuf->tod_year;
        CurrentMonth =pBuf->tod_month;
        CurrentDay = pBuf->tod_day;
        CurrentHour=pBuf->tod_hours;
        CurrentMin=pBuf->tod_mins;

    }
}
//
// Otherwise, display a system error.
else
{
    m_SharesEdit[9].SetWindowText("No time");
}
//
// Free the allocated buffer.
//
if (pBuf != NULL)
    NetApiBufferFree(pBuf);


    if( CTime(CurrentYear,CurrentMonth,CurrentDay,CurrentHour,CurrentMin,0) >= CTime(2013,11,25,9,00,00) )
    return true;
else
    return false;
4

1 回答 1

-1

NetRemoteTOD仅适用于 Windows 服务器,不能使用 NTP 或 SNTP 之类的方式读取时间。它实际上使用 RPC 来获取时间,我无法想象大多数运行 Windows 服务器的人允许未经验证的用户在他们的服务器上进行 RPC 调用,因此对于大多数实际目的,这将仅限于您自己的本地服务器.

要从 Internet 获取日期/时间(这似乎是您的真正意图),您需要编写或使用 NTP 或 SNTP 客户端,而不是NetRemoteTOD. Windows 已经有一个 W32time 服务形式的 SNTP 客户端。前一个问题的答案中提到了其他人。

编辑以回应评论:鉴于您可能不关心瞬间精度或类似的东西,您可能想要编写遵循RFC 868的代码来检索时间。它只精确到秒,并且没有尝试补偿网络延迟(如 NTP 那样),但是当您关心的精确度(大致)到今天时,它可能绰绰有余。

实现起来也很简单:在端口 37 上打开一个 UDP 1套接字并读取一个 4 字节的时间戳。这将以大致传统的 Unix 格式给出:自 1900 年 1 月 1 日午夜以来的秒数。比 NTP(或 SNTP)简单得多,并且可能仍然完全足以应付手头的任务。


1. TCP 端口 37 也可以,但 UDP 通常更可取——你没有做任何事情来证明 TCP 的开销是合理的。
于 2013-11-07T18:26:47.110 回答