首页 >后端开发 >C++ >如何使用C#从NTP服务器中检索准确的时间?

如何使用C#从NTP服务器中检索准确的时间?

Barbara Streisand
Barbara Streisand原创
2025-01-29 00:36:09751浏览

How to Retrieve Accurate Time from an NTP Server Using C#?

>从NTP服务器中检索具有C#

的准确时间

此C#代码段演示了如何从网络时间协议(NTP)服务器中获取当前时间:

<code class="language-csharp">public static DateTime GetNetworkTime()
{
    // Default NTP server address
    string ntpServer = "time.windows.com";

    // NTP packet size
    byte[] ntpData = new byte[48];

    // Configure NTP packet
    ntpData[0] = 0x1B; // Leap indicator, version, and client mode

    // Resolve NTP server IP address
    IPAddress[] addresses = Dns.GetHostAddresses(ntpServer);

    // Create endpoint for NTP server (port 123)
    IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);

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

        // Set receive timeout
        socket.ReceiveTimeout = 3000;

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

    // Offset for server reply time in the NTP packet
    const int serverReplyTimeOffset = 40;

    // Extract timestamp components
    ulong integerPart = BitConverter.ToUInt32(ntpData, serverReplyTimeOffset);
    ulong fractionalPart = BitConverter.ToUInt32(ntpData, serverReplyTimeOffset + 4);

    // Convert to little-endian byte order
    integerPart = SwapEndianness(integerPart);
    fractionalPart = SwapEndianness(fractionalPart);

    // Calculate milliseconds
    long milliseconds = (long)(integerPart * 1000) + (long)((fractionalPart * 1000) / 0x100000000L);

    // Construct DateTime object from NTP timestamp (UTC)
    DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds);

    // Convert to local time
    return networkDateTime.ToLocalTime();
}

// Helper function for byte order conversion
static ulong SwapEndianness(ulong x)
{
    return (ulong)(((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
}</code>
请记住使用语句添加这些:

<code class="language-csharp">using System.Net;
using System.Net.Sockets;</code>
此修订的代码提供了改善的清晰度,并利用了更高效的字节订单交换。 还可以纠正

的功能以进行适当的操作。SwapEndianness>

以上是如何使用C#从NTP服务器中检索准确的时间?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn