C#通过NTP服务器获取NTP时间

C#通过NTP服务器获取NTP时间

注意事项:

  1. 如果NTP服务器地址是域名,如阿里云的NTP服务器地址。需要DNS解析。
  2. NTP使用UDP通讯,默认端口是123
  3. NTP经过很多年的发展,有4个版本号,目前常用的3和4。NTP区分客户端和服务端,客户端角色标志为3。
  4. NTP发送的时间戳是第41到48个字节。获取到的字节需要转为大端序列。
  5. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值