BugFree.Net
1.0.250817.1009
dotnet add package BugFree.Net --version 1.0.250817.1009
NuGet\Install-Package BugFree.Net -Version 1.0.250817.1009
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BugFree.Net" Version="1.0.250817.1009" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BugFree.Net" Version="1.0.250817.1009" />
<PackageReference Include="BugFree.Net" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BugFree.Net --version 1.0.250817.1009
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: BugFree.Net, 1.0.250817.1009"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BugFree.Net@1.0.250817.1009
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BugFree.Net&version=1.0.250817.1009
#tool nuget:?package=BugFree.Net&version=1.0.250817.1009
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
BugFree.Net
跨平台 .NET 网络实用组件。本仓库当前包含 NTP(Network Time Protocol)客户端与轻量级服务器实现,支持 Windows 与 Linux 高精度时钟获取与系统时间校准。
功能特性
- NTP 客户端:
- 多次采样获取平均时间偏移、最小网络延迟与上下行误差(基于 RFC 5905 公式)
- 高精度时间戳:Windows 使用 GetSystemTimePreciseAsFileTime,Linux 使用 clock_gettime
- 轻量级 NTP 服务器:
- 接收线程 + 多工作线程 + 有界通道(削峰、避免拥塞)
- 零分配响应路径(Span/模板写入),按 NTP 64 位时间戳格式返回
- 跨平台时间工具:
- HighPrecisionClock.UtcNow / ToTimestamp()
- HighPrecisionClock.SetSystemTime(utc)(需要管理员/root 权限)
快速开始
客户端示例:
using BugFree.Net.NTP;
var client = new NTPClient { Server = "pool.ntp.org" };
var (avgOffset, minDelay, asym) = client.GetAverageNetworkTimeOffset(6);
Console.WriteLine($"Average Offset: {avgOffset.TotalMilliseconds:F3} ms");
Console.WriteLine($"Min Delay: {minDelay.TotalMilliseconds:F3} ms");
Console.WriteLine($"Asymmetry: {asym.TotalMilliseconds:F3} ms");
// 校正当前 UTC 时间(示例,不直接写系统时钟)
var correctedUtc = DateTime.UtcNow + avgOffset;
服务器示例:
using BugFree.Net.NTP;
using var server = new NTPServer(useIPv6: false);
server.Port = 123; // 注意:绑定 123 端口可能需要管理员/root 权限
server.Start(workers: 4);
Console.WriteLine("NTP server started. Press Enter to exit...");
Console.ReadLine();
API 概览
NTPClient
- 属性
- required string Server:服务器地址(域名或 IP)
- int Port = 123:端口
- 方法
- (TimeSpan averageOffset, TimeSpan minDelay, TimeSpan asymmetry) GetAverageNetworkTimeOffset(int sampleCount)
- void SyncSystemTime(int sampleCount):根据平均偏移设置系统时间(需要管理员/root 权限)
- 属性
NTPServer
- 可配置项
- int Port:监听端口(默认 12345;标准 NTP 为 123)
- bool UseIPv6:是否启用 IPv6(默认 false)
- 方法
- void Start(int workers = 4, CancellationToken token = default)
- void Dispose():释放资源,结束后台线程
- 可配置项
HighPrecisionClock(内部)
- static DateTime UtcNow:高精度 UTC 时间
- static ulong ToTimestamp():转换为 64 位 NTP 时间戳
- static void SetSystemTime(DateTime utc):设置系统时间
权限与平台说明
- 读取时间:不需要提升权限。
- 设置系统时间:
- Windows:调用 SetSystemTime,需要管理员权限(建议以提升权限运行)。
- Linux:调用 /bin/date,需要 root 权限;服务器部署时可使用 sudo。
常见问题 FAQ
- 为什么有时会出现若干次采样失败?
- 网络抖动、DNS 解析失败、目标服务器丢包等都可能导致失败。代码会统计失败次数并继续采样;可适当提高 sampleCount。
- 能否达到亚毫秒级精度?
- 在良好网络与平台支持下,平均偏移可达到毫秒级;亚毫秒需要更严苛的网络与时钟源条件(PTP/硬件时间戳等)。
- 服务器端为何默认端口不是 123?
- 绑定 123 端口通常需要管理员/root 权限;示例默认 12345,实际部署可改回 123。
参考
- RFC 5905: Network Time Protocol Version 4
- Microsoft Docs: GetSystemTimePreciseAsFileTime / SetSystemTime
- Linux man: clock_gettime(2), date(1)
附录:NTP 采样与同步建议
采样次数建议
- 常用推荐值:3~8 次。
- 取多次采样的平均值和最小延迟,可以有效过滤偶发的网络抖动和异常延迟。
- 实际工程经验:
- 3 次:最小,能初步过滤极端值,但抗干扰能力有限。
- 4~5 次:大多数应用场景下足够,既能平滑网络抖动,又不会太耗时。
- 8~10 次:对高精度要求或网络环境较差时可适当增加,但超过 10 次收益递减。
- NTP 协议官方实现(如 ntpd)通常会持续采样并动态调整,但一次性校时时,4~8 次是常见选择。
- 建议:
- 一般应用:4~5 次即可。
- 对时精度要求高或网络不稳定:8 次左右。
- 极端高精度:可采样 10 次以上,并剔除最大/最小值后再取平均。
- 你可以根据实际网络环境和对时精度需求灵活调整采样次数。
校时频率建议(多久同步一次)
NTP(网络时间协议)一般多久校时一次,取决于应用场景和对时精度要求。常见建议如下:
- 桌面/服务器操作系统:
- 通常每 64 秒 ~ 1024 秒(1~17 分钟)自动同步一次。Windows 默认每 1 小时同步一次;Linux 的 ntpd/chronyd 会根据网络状况动态调整,通常在几分钟到几十分钟之间。
- 嵌入式/物联网设备:
- 常见做法是每 10 分钟 ~ 1 小时同步一次。如果设备掉线或唤醒后,也建议立即同步一次。
- 高精度场景:
- 对时精度要求极高(如金融、工业控制),可缩短到每分钟甚至更频繁,但需注意不要对 NTP 服务器造成过大压力。
- 低功耗/低频率场景:
- 对时精度要求不高的设备,可以每几小时甚至每天同步一次。
实际建议:
- 普通应用:每 10~30 分钟同步一次即可。
- 对时精度高:每 1~5 分钟同步一次。
- 低功耗/低频率:每小时或每天同步一次。
上下行不对称延迟对 NTP 的影响
NTP 算法假设“请求(上行)”和“响应(下行)”的网络延迟大致相等。如果上下行延迟差异很大(比如上行 10 ms,下行 100 ms),则公式计算出的 offset 会有较大误差,导致校时不准确。
实际应对:
- 多次采样,取最小延迟的样本:
- 优先采用“最小网络延迟”对应的 offset 作为校时依据,因为最小时延时上下行更可能接近对称,误差更小。
- 剔除异常值:
- 可剔除延迟明显偏大的样本,只用延迟较小的样本计算平均 offset。
- 网络环境优化:
- 尽量保证 NTP 客户端与服务器之间的网络路径稳定、对称,减少上下行延迟差异。
常见网络场景下的上下行延迟误差参考
- 有线以太网(Ethernet)
- 上下行延迟差异极小,通常在 1~5 ms 以内,网络对称性最好。
- 绝大多数情况下可忽略不计。
- 局域网 Wi‑Fi(WLAN)
- 信号好时:5~15 ms
- 信号一般/有干扰时:10~30 ms
- 极端拥塞/弱信号:30 ms 以上
- 4G/5G 蜂窝网络
- 4G:10~30 ms(正常),30~80 ms(拥塞/弱信号),>100 ms(异常)
- 5G:5~20 ms(正常),20~50 ms(拥塞/弱信号)
- 3G 蜂窝网络
- 20~80 ms(正常),>100 ms(拥塞/弱信号)
- 公网/跨运营商/卫星链路
- 公网/跨运营商:20~100 ms,偶尔更高
- 卫星链路:100~500 ms,甚至更高,且极不对称
实际建议:
- 以太网/优质 Wi‑Fi:上下行误差 <10 ms,NTP 校时非常可靠。
- 蜂窝网络:<30 ms 为佳,>50 ms 建议多次采样取最优。
- 公网/卫星:误差大时需剔除异常样本,或考虑更稳健的时钟同步策略。
许可证
本项目采用 Apache License 2.0 开源许可证,详见根目录的 LICENSE
文件。
联系方式
如有问题或建议,请联系邮箱:ligengrong@hotmail.com
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net8.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|---|---|
1.0.250817.1009 | 101 | 8/17/2025 |
1.0.250816.1339 | 57 | 8/16/2025 |
新增/优化 NTP Server/Client;改进并发与延迟表现;完善测试用例与示例。