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)); } } }标签:同步,string,c#,NTP,System,DateTime,SERVER,public,socket From: https://www.cnblogs.com/soulice/p/18222705