c# NTP 时间同步

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
 
namespace SmartConstructionSite.Common.Helper
{
    public class NTPHelper
    {
        public const string WINDOWS_SERVER = "time.windows.com";
        public const string GOOGLE_SERVER = "time.google.com";
        public const string JAPAN_SERVER = "ntp1.jst.mfeed.ad.jp";
        public const string CHINA_SERVER = "cn.pool.ntp.org";
        public const string ALI_SERVER = "ntp.aliyun.com";
 
        /// <summary>
        /// 获取服务器时间
        /// </summary>
        /// <param name="time">UTC时间</param>
        /// <returns></returns>
        private static bool GetNTPTime(out DateTime time, out string error, string server = ALI_SERVER)
        {
            time = DateTime.Now;
            error = "";
            try
            {
                byte[] ntpData = new byte[48];
                ntpData[0] = 0x1B;
                IPAddress[] addresses = Dns.GetHostEntry(server).AddressList;
                IPEndPoint ipEndPoint = new IPEndPoint(addresses[0], 123);
 
                //socket连接
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                socket.Connect(ipEndPoint);
                socket.ReceiveTimeout = 3000;
                socket.Send(ntpData);
                socket.Receive(ntpData);
                socket.Close();
 
                //数据解析
                byte serverReplyTime = 40;
                ulong intPart = System.BitConverter.ToUInt32(ntpData, serverReplyTime);
                ulong fractPart = System.BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
                intPart = SwapEndianness(intPart);
                fractPart = SwapEndianness(fractPart);
 
                ulong milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
                time = (new System.DateTime(1900, 1, 1, 0, 0, 0, System.DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
                return true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }
        public static DateTime GetNTPTime()
        {
            DateTime dateTime;
            if (NTPHelper.GetNTPTime(out DateTime time, out string error, NTPHelper.WINDOWS_SERVER))
            {
                dateTime = time;
            }
            else
            {
                //同步失败
                dateTime = DateTime.MinValue;
            }
            return dateTime;
 
        }
 
        /// <summary>
        /// 大小端互换
        /// </summary>
        /// <param name="x"></param>
        /// <returns></returns>
        private static uint SwapEndianness(ulong x)
        {
            return (uint)(((x & 0x000000ff) << 24) +
                           ((x & 0x0000ff00) << 8) +
                           ((x & 0x00ff0000) >> 8) +
                           ((x & 0xff000000) >> 24));
        }
    }
}
posted @   wolfsocket  阅读(87)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示