通过阿里云获取互联网时间

 #region 获取互联网时间
        private static string[] Servers = { "ntp.aliyun.com",
                                            "ntp1.aliyun.com",
                                            "ntp2.aliyun.com",
                                            "ntp3.aliyun.com",
                                            "ntp4.aliyun.com",
                                            "ntp5.aliyun.com",
                                            "ntp6.aliyun.com",
                                            "ntp7.aliyun.com"
                                            };
        private void button1_Click_1(object sender, EventArgs e)
        {
            foreach (string server in Servers)
            {
                string ntpServer = server;
                var ntpData = new byte[48];
                ntpData[0] = 0x1B;
                try
                {
                    var addresses = Dns.GetHostEntry(ntpServer).AddressList;
                    var ipEndPoint = new IPEndPoint(addresses[0], 123);
                    var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    socket.Connect(ipEndPoint);
                    socket.ReceiveTimeout = 3000;
                    socket.Send(ntpData);
                    socket.Receive(ntpData);
                    socket.Close();
                }
                catch (Exception ex)
                {
                    continue;
                }
                const byte serverReplyTime = 40;
                ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
                ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
                intPart = SwapEndianness(intPart);
                fractPart = SwapEndianness(fractPart);
                var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
                //计算后的时间
                var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
            }
            uint SwapEndianness(ulong x)
            {
                return (uint)(((x & 0x000000ff) << 24) +
                ((x & 0x0000ff00) << 8) +
                ((x & 0x00ff0000) >> 8) +
                ((x & 0xff000000) >> 24));
            }
        }
        #endregion

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值