C#获取内网NTP服务器时间(通过IP或者域名)

不废话直接上代码,需要拿去,内网自己的时间服务器,通过IP配置

    public class NTPTimeHelper
    {
        /// <summary>
        /// 获取NTP时间(时间服务器)
        /// </summary>
        /// <returns></returns>
        public static DateTime GetNetworkTime()
        {
            try
            {
                //default Windows time server
                //用域名获取时候用这里
                //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) {52.231.114.183
                //用域名获取时候用这里
                //var addresses = Dns.GetHostEntry(ntpServer).AddressList;
                IPAddress[] IPAddressList = new IPAddress[1];
                //配置时间服务器IP
                IPAddress address = new IPAddress(new byte[] { 192, 168, 1, 1 });
                IPAddressList[0] = address;
                //The UDP port number assigned to NTP is 123
                var ipEndPoint = new IPEndPoint(IPAddressList[0], Convert.ToInt32(123));
                //NTP uses UDP
                var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.Connect(ipEndPoint);
                //Stops code hang if NTP is blocked
                socket.ReceiveTimeout = 1000;

                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();
            }
            catch (Exception ex)
            {
                return DateTime.Now;
            }

        }
        static uint SwapEndianness(ulong x)
        {
            return (uint)(((x & 0x000000ff) << 24) +
            ((x & 0x0000ff00) << 8) +
            ((x & 0x00ff0000) >> 8) +
            ((x & 0xff000000) >> 24));
        }
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值