使用NTP可能存在风险(例如服务器关闭) [英] Possible risk(e.g. server down) using NTP

查看:404
本文介绍了使用NTP可能存在风险(例如服务器关闭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中有以下代码。我正在使用服务器asia.pool.ntp.org来获取返回的时间。有没有可能asia.pool.ntp.org关闭,当我打电话给服务器时它会返回异常?

以下是我的代码:



Hi, I have the following codes in C#. I am using a server "asia.pool.ntp.org" to get the time returned. Is there any possibility that the "asia.pool.ntp.org" is down and it will return exception when I call the server?
Below are my codes:

public static DateTime GetNetworkTime()
{
    //default Windows time server
    //asia.pool.ntp.org
    const string ntpServer = "asia.pool.ntp.org";

    // NTP message size - 16 bytes of the digest (RFC 2030)
    var ntpData = new byte[48];

    //Setting the Leap Indicator, Version Number and Mode values
    ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

    var addresses = Dns.GetHostEntry(ntpServer).AddressList;

    //The UDP port number assigned to NTP is 123
    var ipEndPoint = new IPEndPoint(addresses[0], 123);
    //NTP uses UDP
    var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

    socket.Connect(ipEndPoint);

    //Stops code hang if NTP is blocked
    socket.ReceiveTimeout = 5000;

    socket.Send(ntpData);
    socket.Receive(ntpData);
    socket.Close();

    //Offset to get to the "Transmit Timestamp" field (time at which the reply
    //departed the server for the client, in 64-bit timestamp format."
    const byte serverReplyTime = 40;

    //Get the seconds part
    ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

    //Get the seconds fraction
    ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

    //Convert From big-endian to little-endian
    intPart = SwapEndianness(intPart);
    fractPart = SwapEndianness(fractPart);

    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

    //**UTC** time
    var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

    return networkDateTime.ToUniversalTime();
}

推荐答案

是的,如果NTP服务器处于脱机状态,则会抛出异常。如果您查看 Socekt.Connect 的MSDN文档[ ^ ],你会看到它可以抛出的异常列表。



如果我的记忆正确地为我服务,你应该得到一个SocketException,其中的细节是连接超时的。最简单的测试方法是修改主机文件,将asia.pool.ntp.org指向127.0.0.1,以便它尝试使用本地计算机提取时间信息。这将模拟它们离线。
Yes, there is an exception that is thrown if the NTP server is offline. If you look at the MSDN documentation for Socekt.Connect[^], you will see the list of exceptions that it could throw.

If my memory serves me correctly, you should get a SocketException with the details being connection timed out. The easiest way to test this is to modify your host file to point asia.pool.ntp.org to 127.0.0.1 so that it tries to use your local machine to pull the time information. This will simulate them being offline.


这篇关于使用NTP可能存在风险(例如服务器关闭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆