C# 获取网络时间 使用 NTP

 static DateTime GetDate()
 {
     // NTP 服务器地址和端口  
     string ntpServer = "ntp.aliyun.com"; // 使用公共 NTP 服务器  
     int ntpPort = 123;

     // 创建 UDP 客户端  
     using (Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
     {
         try
         {
             // 连接到 NTP 服务器  
             udpClient.Connect(ntpServer, ntpPort);

             // 构建 NTP 请求数据包  
             byte[] requestData = new byte[48];
             requestData[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (Client Mode)  

             // 发送 NTP 请求  
             udpClient.Send(requestData);

             // 接收 NTP 响应  
             byte[] responseData = new byte[48];
             int bytesRead = udpClient.Receive(responseData);

             // 解析 NTP 响应以获取时间  
             if (bytesRead == 48)
             {
                 ulong intPart = BitConverter.ToUInt32(responseData.Skip(40).Take(4).Reverse().ToArray(), 0);
                 ulong fracPart = BitConverter.ToUInt32(responseData.Skip(44).Take(4).Reverse().ToArray(), 0);
                 // 将分数部分从固定点数(Q32.32)转换为秒的小数部分(假设 fracPart 已经是 Big-Endian)  
                 double fracSeconds = (fracPart / (double)uint.MaxValue) / (double)uint.MaxValue; // 或者使用 (fracPart / 4294967296.0) 但注意精度损失问题(这里使用 uint.MaxValue 来提高精度)  

                 // 将 NTP 时间转换为 DateTime  
                 DateTime networkDateTime = DateTimeOffset.FromUnixTimeSeconds((long)(intPart - 2208988800UL)).AddSeconds(fracSeconds).ToUniversalTime().LocalDateTime;

                 //  networkDateTime = networkDateTime.AddMilliseconds((double));
                 return networkDateTime;

             }
         }
         catch (Exception) { }
         return DateTime.MinValue;
     }
 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值