首页 > 后端开发 > C++ > 如何使用C#查询当前日期和时间的NTP服务器?

如何使用C#查询当前日期和时间的NTP服务器?

Barbara Streisand
发布: 2025-01-29 00:31:09
原创
810 人浏览过

How to Query an NTP Server for Current Date and Time Using C#?

使用C#查询NTP服务器:完整解决方案

本文提供一种可靠的方法,使用C#从NTP服务器检索当前日期和时间。以下是涉及的步骤和完整的代码解决方案。

此方法依赖于网络时间协议(NTP),它涉及向NTP服务器发送查询消息。服务器会回复包含当前时间的回复消息。然后,我们从回复中提取时间并将其转换为可用的格式。

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

public static class NTP
{
    public static DateTime GetNetworkTime()
    {
        const string ntpServer = "time.windows.com";
        const int ntpPort = 123;
        byte[] ntpData = new byte[48];

        ntpData[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (Client)

        using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            socket.Connect(new IPEndPoint(Dns.GetHostEntry(ntpServer).AddressList[0], ntpPort));

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

        const int serverReplyTime = 40;
        ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
        ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);

        long milliseconds = (long)(intPart * 1000) + (long)((fractPart * 1000) / 0x100000000L);
        DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds);

        return networkDateTime.ToLocalTime();
    }

    private static ulong SwapEndianness(ulong x)
    {
        return (ulong)(
            ((x & 0x000000ff) << 24) |
            ((x & 0x0000ff00) << 8) |
            ((x & 0x00ff0000) >> 8) |
            ((x & 0xff000000) >> 24)
        );
    }
}
登录后复制

使用此代码,您可以轻松查询NTP服务器并获取当前日期和时间。此解决方案处理字节序转换,并提供了一种灵活的方式来从任何兼容的NTP服务器检索时间。 注意代码中SwapEndianness函数的修正,以确保正确的字节序转换。

以上是如何使用C#查询当前日期和时间的NTP服务器?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板