• 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

    感谢阅读

  • 相关阅读:
    在浏览器中输入URL并回车后都发生了什么?
    HashMap数据结构
    记录一次mysql死锁
    常见排序(归并排序)
    记录一次redis事故
    jsp与javaBean
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.zhuoshi.entity.Dep#1]
    Oracle创建表空间报错:O/S-Error: (OS 3) 系统找不到指定的路径
    在myeclipse中maven项目关于ssh整合时通过pom.xml导入依赖是pom.xml头部会报错
    2018idea如何布置tomcat修改URL后连接不到
  • 原文地址:https://www.cnblogs.com/congqiandehoulai/p/8523373.html
Copyright © 2020-2023  润新知