如何使用 C#.NET 代码查询 NTP 服务器上 time.windows.com 日期
本文关键字:time windows com 日期 服务器 NTP 何使用 NET 代码 查询 | 更新日期: 2023-09-27 18:35:35
可能的重复项:
如何从 C# 查询 NTP 服务器
我正在尝试从time.windows.com
NTP服务器获取日期时间,我使用以下代码:
using System;
using System.IO;
using System.Net.Sockets;
namespace ntpdate2
{
class MainClass
{
public static void Main (string[] args)
{
var client = new TcpClient("time.windows.com", 123);
client.SendTimeout = 60;
using (var streamReader = new StreamReader(client.GetStream()))
{
var response = streamReader.ReadToEnd();
Console.WriteLine(response);
streamReader.Close();
}
}
}
}
但它给出了一个:
Unhandled Exception: System.Net.Sockets.SocketException: Connection timed out
at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remote_end) [0x00000]
at System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint remote_end_point) [0x00000]
at System.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[] ipAddresses, Int32 port) [0x00000]
The application was terminated by a signal: SIGHUP
如何解决这个问题?提前谢谢。
这是在 LINQPad 中运行的代码,在 https://mschwarztoolkit.svn.codeplex.com/svn/NTP/NtpClient.cs 处与原始版本略有修改
void Main()
{
var x = NtpClient.GetNetworkTime();
x.Dump();
}
/// <summary>
/// Static class to receive the time from a NTP server.
/// </summary>
public class NtpClient
{
/// <summary>
/// Gets the current DateTime from time-a.nist.gov.
/// </summary>
/// <returns>A DateTime containing the current time.</returns>
public static DateTime GetNetworkTime()
{
return GetNetworkTime("time.windows.com"); // time-a.nist.gov
}
/// <summary>
/// Gets the current DateTime from <paramref name="ntpServer"/>.
/// </summary>
/// <param name="ntpServer">The hostname of the NTP server.</param>
/// <returns>A DateTime containing the current time.</returns>
public static DateTime GetNetworkTime(string ntpServer)
{
IPAddress[] address = Dns.GetHostEntry(ntpServer).AddressList;
if(address == null || address.Length == 0)
throw new ArgumentException("Could not resolve ip address from '" + ntpServer + "'.", "ntpServer");
IPEndPoint ep = new IPEndPoint(address[0], 123);
return GetNetworkTime(ep);
}
/// <summary>
/// Gets the current DateTime form <paramref name="ep"/> IPEndPoint.
/// </summary>
/// <param name="ep">The IPEndPoint to connect to.</param>
/// <returns>A DateTime containing the current time.</returns>
public static DateTime GetNetworkTime(IPEndPoint ep)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
s.Connect(ep);
byte[] ntpData = new byte[48]; // RFC 2030
ntpData[0] = 0x1B;
for (int i = 1; i < 48; i++)
ntpData[i] = 0;
s.Send(ntpData);
s.Receive(ntpData);
byte offsetTransmitTime = 40;
ulong intpart = 0;
ulong fractpart = 0;
for (int i = 0; i <= 3; i++)
intpart = 256 * intpart + ntpData[offsetTransmitTime + i];
for (int i = 4; i <= 7; i++)
fractpart = 256 * fractpart + ntpData[offsetTransmitTime + i];
ulong milliseconds = (intpart * 1000 + (fractpart * 1000) / 0x100000000L);
s.Close();
TimeSpan timeSpan = TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
DateTime dateTime = new DateTime(1900, 1, 1);
dateTime += timeSpan;
TimeSpan offsetAmount = TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
DateTime networkDateTime = (dateTime + offsetAmount);
return networkDateTime;
}
}