C#通过NTP服务器获取NTP时间
注意事项:
- 如果NTP服务器地址是域名,如阿里云的NTP服务器地址。需要DNS解析。
- NTP使用UDP通讯,默认端口是123
- NTP经过很多年的发展,有4个版本号,目前常用的3和4。NTP区分客户端和服务端,客户端角色标志为3。
- NTP发送的时间戳是第41到48个字节。获取到的字节需要转为大端序列。
- NTP标准协议返回的时间是自1900.1.1 00:00:00开始的毫秒时间数值,需要字节转换为你需要的日期时间。
以下是通过NTP服务器获取NTP时间的代码:
/// <summary>
/// 获取NTP时间
/// </summary>
/// <param name="serverList"></param>
/// <param name="timeoutMilliseconds"></param>
/// <param name="isToLocal"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public static async Task<DateTime> GetNtpTime(List<string> serverList, bool isToLocal = false, int timeoutMilliseconds = 2000)
{
List<string> realServerList = new List<string>();
bool needUseLastIp = false;
if (serverList is null || !serverList.Any())
{
serverList = NtpServers;
needUseLastIp = true;
if (!string.IsNullOrEmpty(lastIpAddress))
{
realServerList.Add(lastIpAddress);
if (serverList.Contains(lastIpAddress))
{
serverList.Remove(lastIpAddress

最低0.47元/天 解锁文章
681

被折叠的 条评论
为什么被折叠?



