c#获取网络时间并同步本地时间

通过TCP形式来获取NTP时间。主要代码如下:

 [DllImport("kernel32.dll")]
        private static extern bool SetLocalTime(ref Systemtime time);

        [StructLayout(LayoutKind.Sequential)]
        private struct Systemtime
        {
            public short year;
            public short month;
            public short dayOfWeek;
            public short day;
            public short hour;
            public short minute;
            public short second;
            public short milliseconds;
        }

        /// <summary>
        /// 设置系统时间
        /// </summary>
        /// <param name="dt">需要设置的时间</param>
        /// <returns>返回系统时间设置状态,true为成功,false为失败</returns>
        public static bool SetLocalDateTime(DateTime dt)
        {
            Systemtime st;

            st.year = (short)dt.Year;
            st.month = (short)dt.Month;
            st.dayOfWeek = (short)dt.DayOfWeek;
            st.day = (short)dt.Day;
            st.hour = (short)dt.Hour;
            st.minute = (short)dt.Minute;
            st.second = (short)dt.Second;
            st.milliseconds = (short)dt.Millisecond;
            bool rt = SetLocalTime(ref st);
            return rt;
        }


        public static DateTime GetDateTime(long timeStamp)
        {
            return new DateTime(1970, 1, 1).AddSeconds(timeStamp).ToLocalTime();
        }

        public static bool GetInternetTime(string url, out DateTime dt, out string errMsg)
        {
            dt = DateTime.MinValue;
            var startDt = DateTime.Now;
            var port = 13;
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveTimeout = 2000 };
            try
            {
                var iphostinfo = Dns.GetHostEntry(url);
                var ip = iphostinfo.AddressList[0];
                var ipe = new IPEndPoint(ip, port);

                var iar = socket.BeginConnect(ipe, null, null);
                if (!iar.AsyncWaitHandle.WaitOne(5000))
                {
                    errMsg = "连接超时" + url;
                    return false;
                }
                var recvBuffer = new byte[1024];
                var sb = new StringBuilder();
                var myE = Encoding.UTF8;

                int nBytes;
                while ((nBytes = socket.Receive(recvBuffer, 0, 1024, SocketFlags.None)) > 0)
                {
                    sb.Append(myE.GetString(recvBuffer, 0, nBytes));
                }
                var o = sb.ToString().Split(' ');


                TimeSpan ts = DateTime.Now - startDt;

                var setDt = Convert.ToDateTime(o[1] + " " + o[2]).Subtract(-ts); // 减去中途消耗的时间


                dt = setDt.ToLocalTime();
                Console.WriteLine(@"服务器:{0}时间:{1}", url, setDt);
                errMsg = "";
                return true;
            }
            catch (Exception ex)
            {

                errMsg = ex.Message;
                return false;
            }
            finally
            {
                socket.Close();
            }
        }

  

源码如下:

https://files.cnblogs.com/files/lizhijian/%E8%8E%B7%E5%8F%96%E7%BD%91%E7%BB%9C%E6%97%B6%E9%97%B4.rar

 

 

感谢阅读

转载于:https://www.cnblogs.com/chlm/p/8523373.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值