2026-10-19 22:04:19 +08:00

87 lines
4.0 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace YuncangTrace.LocalService.Services;
/// <summary>一次 SNTP 查询的结果</summary>
/// <param name="Server">使用的 NTP 服务器(用户填的地址)</param>
/// <param name="ServerTime">服务器给出的当前时间(本地时区表示)</param>
/// <param name="Offset">服务器时间 - 本机时间(正数表示本机慢了)</param>
/// <param name="RoundTrip">一次 UDP 往返耗时</param>
public sealed record NtpResult(string Server, DateTimeOffset ServerTime, TimeSpan Offset, TimeSpan RoundTrip);
/// <summary>
/// 极简 SNTP 客户端(UDP 123,RFC 2030 / 4330),不依赖 Windows 时间服务。
///
/// 为什么自己实现:现场很多电脑的 Windows Time 服务根本没启动(`w32tm` 报 0x80070426),
/// 时间慢慢漂到差十秒;而回放是按录像机时间定位的,差几秒就会把面单截掉。
/// 这里直接向 NTP 服务器取时间,由本软件写回系统时钟;写时钟需要管理员权限,
/// 非管理员时由 <see cref="ElevatedNtp"/> 拉起提权 helper 完成。
/// </summary>
public static class NtpClient
{
/// <summary>NTP 的 1900-01-01 到 1970-01-01 之间的秒数</summary>
private const uint NtpEpochOffset = 2208988800u;
/// <summary>默认端口</summary>
public const int NtpPort = 123;
/// <summary>
/// 查询 NTP 服务器时间。
/// </summary>
/// <param name="server">域名或 IP(如 ntp.aliyun.com / 112.124.21.102)</param>
/// <param name="timeoutMs">超时(毫秒)</param>
public static async Task<NtpResult> QueryAsync(string server, int timeoutMs = 3000, CancellationToken ct = default)
{
var host = (server ?? string.Empty).Trim();
if (host.Length == 0) throw new ArgumentException("请填写 NTP 服务器地址");
var addresses = await Dns.GetHostAddressesAsync(host, ct).ConfigureAwait(false);
var address = addresses.FirstOrDefault(item => item.AddressFamily == AddressFamily.InterNetwork)
?? addresses.FirstOrDefault()
?? throw new InvalidOperationException($"解析不到 NTP 服务器:{host}");
using var udp = new UdpClient(address.AddressFamily);
udp.Connect(address, NtpPort);
// LI = 0(无闰秒警告),VN = 3,Mode = 3(客户端)
var request = new byte[48];
request[0] = 0x1B;
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
timeout.CancelAfter(timeoutMs);
try
{
var t1 = DateTime.UtcNow;
await udp.SendAsync(request.AsMemory(), timeout.Token).ConfigureAwait(false);
var response = await udp.ReceiveAsync(timeout.Token).ConfigureAwait(false);
var t4 = DateTime.UtcNow;
var data = response.Buffer;
if (data.Length < 48) throw new InvalidOperationException("NTP 响应格式不正确(长度不足 48 字节)");
// 服务器发包时间(Transmit Timestamp,bytes 40~47)
var seconds = ((uint)data[40] << 24 | (uint)data[41] << 16 | (uint)data[42] << 8 | data[43]) - NtpEpochOffset;
var fraction = ((uint)data[44] << 24 | (uint)data[45] << 16 | (uint)data[46] << 8 | data[47]) / 4294967296.0;
var serverUtc = DateTime.UnixEpoch.AddSeconds(seconds + fraction);
// 用「本机发送/接收的中点」估算单程延迟,得到偏差
var midpoint = t1.AddTicks((t4 - t1).Ticks / 2);
var offset = serverUtc - midpoint;
var result = new NtpResult(host, new DateTimeOffset(serverUtc, TimeSpan.Zero).ToLocalTime(),
offset, t4 - t1);
return result;
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException($"连接 NTP 服务器超时({host}:{NtpPort},{timeoutMs} ms)");
}
}
}