static DateTime GetDate()
{
// NTP 服务器地址和端口
string ntpServer = "ntp.aliyun.com"; // 使用公共 NTP 服务器
int ntpPort = 123;
// 创建 UDP 客户端
using (Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
try
{
// 连接到 NTP 服务器
udpClient.Connect(ntpServer, ntpPort);
// 构建 NTP 请求数据包
byte[] requestData = new byte[48];
requestData[0] = 0x1B; // LI = 0, VN = 3, Mode = 3 (Client Mode)
// 发送 NTP 请求
udpClient.Send(requestData);
// 接收 NTP 响应
byte[] responseData = new byte[48];
int bytesRead = udpClient.Receive(responseData);
// 解析 NTP 响应以获取时间
if (bytesRead == 48)
{
ulong intPart = BitConverter.ToUInt32(responseData.Skip(40).Take(4).Reverse().ToArray(), 0);
ulong fracPart = BitConverter.ToUInt32(responseData.Skip(44).Take(4).Reverse().ToArray(), 0);
// 将分数部分从固定点数(Q32.32)转换为秒的小数部分(假设 fracPart 已经是 Big-Endian)
double fracSeconds = (fracPart / (double)uint.MaxValue) / (double)uint.MaxValue; // 或者使用 (fracPart / 4294967296.0) 但注意精度损失问题(这里使用 uint.MaxValue 来提高精度)
// 将 NTP 时间转换为 DateTime
DateTime networkDateTime = DateTimeOffset.FromUnixTimeSeconds((long)(intPart - 2208988800UL)).AddSeconds(fracSeconds).ToUniversalTime().LocalDateTime;
// networkDateTime = networkDateTime.AddMilliseconds((double));
return networkDateTime;
}
}
catch (Exception) { }
return DateTime.MinValue;
}
}
04-13
1779