莱莱 发表于 2024-5-20 07:13:36

.NET实现获取NTP服务器时间并同步(附带Windows系统启用NTP服务功能)

对某个远程服务器启用和设置NTP服务(Windows系统)
打开注册表
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\W32Time\TimeProviders\NtpServer
将 Enabled 的值设置为 1,这将启用NTP服务器功能。
https://alidocs.dingtalk.com/core/api/resources/img/5eecdaf48460cde5ed77e64d8270ad887b210bb78a460d344e47bcdad4e608bc1e41b09a7914ef7b65a117e9692870642ee6e7326510d7270ff13d90525f45c83c7857216a15702d7fe79b22b0a276d7c0f7464fa51c2bfdbbb8e147348d6c36?tmpCode=5cba23d5-d87e-4f69-9c34-02856a969da9
防火墙开放UDP 123端口
https://alidocs.dingtalk.com/core/api/resources/img/5eecdaf48460cde5ed77e64d8270ad887b210bb78a460d344e47bcdad4e608bc1e41b09a7914ef7b65a117e96928706453d56808946c048d5245d7a2775ac0020e980d14042d7700787dcbc9ccb3d6c13a61f87c6fe5758f149565b860957ab4?tmpCode=5cba23d5-d87e-4f69-9c34-02856a969da9
打开“服务”应用(可以在开始菜单搜索“服务”),找到“Windows Time”服务。右键点击“Windows Time”服务,选择“重启”。
https://alidocs.dingtalk.com/core/api/resources/img/5eecdaf48460cde5ed77e64d8270ad887b210bb78a460d344e47bcdad4e608bc1e41b09a7914ef7b65a117e9692870641d7803a81641cbcda750d3d640bfbc5ff7cd9ba4f66edb32a998e3370d249cf72f45b80d7850c2b6a5f44275aa76f220?tmpCode=5cba23d5-d87e-4f69-9c34-02856a969da9
实验以下命令来配置服务器模式并重启时间服务:
w32tm /config /reliable:YES /update
net stop w32time
net start w32time 
https://alidocs.dingtalk.com/core/api/resources/img/5eecdaf48460cde5ed77e64d8270ad887b210bb78a460d344e47bcdad4e608bc1e41b09a7914ef7b65a117e969287064b2f5689bbea3522fa34a5a36f2d67a02dba6c0f94aff5cc2fa71370333393b0f8520cfdbb246ec53f2ac17fb040400bd?tmpCode=5cba23d5-d87e-4f69-9c34-02856a969da9
客户端上面,输入以下命令,更换你本身的NTP服务端IP即可,如果显示类似以下的时间输出,说明是正常的。
w32tm /stripchart /computer:ip地址 /samples:5 /dataonly 
https://alidocs.dingtalk.com/core/api/resources/img/5eecdaf48460cde5ed77e64d8270ad887b210bb78a460d344e47bcdad4e608bc1e41b09a7914ef7b65a117e969287064435941fcb230dd6ff7b4ae4f6800cf11be8c31da59b62daed5cb3752e4d4fd8d9bdce892205f6779985ea16e2deb3474?tmpCode=5cba23d5-d87e-4f69-9c34-02856a969da9
 编写程序,举行时间同步
引用包Wesky.Net.OpenTools ,版本选择1.0.6或以上版本。
https://img2024.cnblogs.com/blog/1995789/202405/1995789-20240515174328030-21461770.png
 
该包的自述文件内容供参考:
https://www.nuget.org/packages/Wesky.Net.OpenTools/1.0.6#readme-body-tab
https://img2024.cnblogs.com/blog/1995789/202405/1995789-20240515174452191-1750930912.png
 在程序里面使用,以下测试内容供参考。其中,ntpServer可以是ip地点也可以是ntp服务器的域名地点或者互联网ntp服务器地点等。获取时间默认端标语没指定的话是123,如果要指定,只需要在参数里面新增端标语参数即可。
https://alidocs.dingtalk.com/core/api/resources/img/5eecdaf48460cde5ed77e64d8270ad887b210bb78a460d344e47bcdad4e608bc1e41b09a7914ef7b65a117e969287064d4b0a242003e54d27f946485a18bce681c0d369530aa743c01b63c575d8f810286a2056719777273e2835520bce621d8?tmpCode=5cba23d5-d87e-4f69-9c34-02856a969da9
 
static void Main(string[] args)
{
    string ntpServer = "ip";
    Console.WriteLine($"当前时间:\r\n{ DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ms")}");
    DateTime time = NtpClient.GetNtpServerTime(ntpServer);
    Console.WriteLine($"获取到的时间为:\r\n {time.ToString("yyyy/MM/dd HH:mm:ss ms")}");
    NtpClient.SetSystemTime(time);
    Console.WriteLine($"更改后的系统时间:\r\n{ DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss ms")}");
    Console.ReadLine();
}获取ntp服务器时间核心代码解析如下:
1 /// <summary>
2 /// 获取NTP服务器的时间。
3 /// Retrieves the time from an NTP server.
4 /// </summary>
5 /// <param name="ntpServer">NTP服务器地址 | NTP server address</param>'
6 /// <param name="ntpPort">NTP服务的端口 | NTP service port</param>
7 /// <returns>服务器时间 | Server time</returns>
8 public static DateTime GetNtpServerTime(string ntpServer,int ntpPort=123)
9 {
10   // 初始化NTP数据缓冲区
11   // Initialize NTP data buffer
12   byte[] ntpData = new byte;
13   ntpData = 0x1B; // NTP version number (3) and mode (3), client request
14
15   var addresses = Dns.GetHostAddresses(ntpServer);
16   IPEndPoint ipEndPoint = new IPEndPoint(addresses, ntpPort);
17
18   using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
19   {
20         socket.Connect(ipEndPoint);
21         socket.Send(ntpData);
22         socket.Receive(ntpData);
23   }
24
25   // 从字节40和44提取时间戳
26   // Extract timestamp from bytes 40 and 44
27   ulong intPart = BitConverter.ToUInt32(ntpData, 40);
28   ulong fractPart = BitConverter.ToUInt32(ntpData, 44);
29
30   // 转换字节序为小端格式
31   // Convert byte order to little endian
32   intPart = SwapEndianness(intPart);
33   fractPart = SwapEndianness(fractPart);
34
35   var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
36
37   // NTP时间是从1900年开始计算的,这里将其转换为UTC时间
38   // NTP time starts from 1900, this converts it to UTC DateTime
39   DateTime networkDateTime = new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long)milliseconds);
40
41   return networkDateTime.ToLocalTime();
42 } 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: .NET实现获取NTP服务器时间并同步(附带Windows系统启用NTP服务功能)