c# - 如何使用 C# 查询 NTP 服务器?

标签 c# datetime ntp

我所需要的只是一种使用 C# 查询 NTP 服务器的方法,以获取作为 stringDateTime 返回的 NTP 服务器的日期时间。

这怎么可能是最简单的形式?

最佳答案

由于旧的已接受答案已被删除(它是指向不再存在的 Google 代码搜索结果的链接),我想我可以回答这个问题以供将来引用:

public static DateTime GetNetworkTime()
{
    //default Windows time server
    const string ntpServer = "time.windows.com";

    // 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

    using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        socket.Connect(ipEndPoint);

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

        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.ToLocalTime();
}

// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
    return (uint) (((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
}

注意:您必须添加以下命名空间

using System.Net;
using System.Net.Sockets;

关于c# - 如何使用 C# 查询 NTP 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1193955/

相关文章:

c# - 为什么 .Net Framework 的加密如此复杂?

iphone - 是否有框架或库和 Web 服务来通过 NTP 以毫秒精度获取原子钟时间?

kubernetes - Kubernetes节点的时间同步问题

python - 在python中获取本周的开始和结束时间戳

r - 将一位数的月和日转换为 POSIXct

android - 在智能手机和个人电脑/嵌入式设备之间同步时间

c# - 如何将 .xproj 引用到 .csproj 中?

javascript - 从数组中删除项目的更好方法

c# - 要命令的 XAML Setter 属性

java - 将多个日期字符串转换为长字符串