• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

通过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

 

 

感谢阅读


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#图片旋转发布时间:2022-07-18
下一篇:
C#中如何下载大文件、隐藏文件真实地址发布时间:2022-07-18
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap