如何使用C#.NET代码在time.windows.com NTP服务器上查询日期?

如何使用C#.NET代码在time.windows.com NTP服务器上查询日期?,c#,datetime,C#,Datetime,可能重复: 我正在尝试从time.windows.comNTP服务器获取日期时间,我正在使用以下代码: using System; using System.IO; using System.Net.Sockets; namespace ntpdate2 { class MainClass { public static void Main (string[] args) { var client = new TcpCl

可能重复:

我正在尝试从
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中运行的代码,在

void Main()
{
var x=NtpClient.GetNetworkTime();
x、 Dump();
}
/// 
///用于从NTP服务器接收时间的静态类。
/// 
公共类NtpClient
{
/// 
///从time-a.nist.gov获取当前日期时间。
/// 
///包含当前时间的日期时间。
公共静态日期时间GetNetworkTime()
{
返回GetNetworkTime(“time.windows.com”);//time-a.nist.gov
}
/// 
///从获取当前日期时间。
/// 
///NTP服务器的主机名。
///包含当前时间的日期时间。
公共静态日期时间GetNetworkTime(字符串ntpServer)
{
IPAddress[]address=Dns.GetHostEntry(ntpServer.AddressList);
如果(地址==null | |地址.长度==0)
抛出新的ArgumentException(“无法从“+ntpServer+”.”、“ntpServer”解析ip地址);
IPEndPoint ep=新的IPEndPoint(地址[0],123);
返回GetNetworkTime(ep);
}
/// 
///获取当前日期时间表单IPEndPoint。
/// 
///要连接到的IPEndPoint。
///包含当前时间的日期时间。
公共静态日期时间GetNetworkTime(IPEndPoint ep)
{
Socket s=新套接字(AddressFamily.InterNetwork、SocketType.Dgram、ProtocolType.Udp);
s、 连接(ep);
字节[]ntpData=新字节[48];//RFC 2030
ntpData[0]=0x1B;
对于(int i=1;i<48;i++)
ntpData[i]=0;
s、 发送(ntpData);
s、 接收(ntpData);
字节偏移传输时间=40;
ulong intpart=0;
ulong fractpart=0;

对于(inti=0;i,这里是在LINQPad中运行的代码,在

void Main()
{
var x=NtpClient.GetNetworkTime();
x、 Dump();
}
/// 
///用于从NTP服务器接收时间的静态类。
/// 
公共类NtpClient
{
/// 
///从time-a.nist.gov获取当前日期时间。
/// 
///包含当前时间的日期时间。
公共静态日期时间GetNetworkTime()
{
返回GetNetworkTime(“time.windows.com”);//time-a.nist.gov
}
/// 
///从获取当前日期时间。
/// 
///NTP服务器的主机名。
///包含当前时间的日期时间。
公共静态日期时间GetNetworkTime(字符串ntpServer)
{
IPAddress[]address=Dns.GetHostEntry(ntpServer.AddressList);
如果(地址==null | |地址.长度==0)
抛出新的ArgumentException(“无法从“+ntpServer+”.”、“ntpServer”解析ip地址);
IPEndPoint ep=新的IPEndPoint(地址[0],123);
返回GetNetworkTime(ep);
}
/// 
///获取当前日期时间表单IPEndPoint。
/// 
///要连接到的IPEndPoint。
///包含当前时间的日期时间。
公共静态日期时间GetNetworkTime(IPEndPoint ep)
{
Socket s=新套接字(AddressFamily.InterNetwork、SocketType.Dgram、ProtocolType.Udp);
s、 连接(ep);
字节[]ntpData=新字节[48];//RFC 2030
ntpData[0]=0x1B;
对于(int i=1;i<48;i++)
ntpData[i]=0;
s、 发送(ntpData);
s、 接收(ntpData);
字节偏移传输时间=40;
ulong intpart=0;
ulong fractpart=0;

for(int i=0;i NTP是UDP协议,而不是TCP。@HansPassant:谢谢,我会修复它。@KenWhite:它对你有用?我尝试过使用类似的代码,但我得到了一个“无限循环”而不是上面的例外。我认为它是有效的,因为答案被接受并获得了16票。恐怕我没有时间亲自测试每一个问题和答案。:-)第二个答案还有一个链接,指向使用同样具有UPVOUTS的解决方案的其他示例。经过测试,链接的代码有效。NTP是UDP协议,而不是TCP。@HansPassant:谢谢,我会修复它。@KenWhite:它对你有效?我尝试过使用类似的代码,但我得到了一个“无限循环”而不是上面的例外。我认为它是有效的,因为答案被接受并获得了16票。恐怕我没有时间亲自测试每一个问题和答案。:-)第二个答案还有一个链接,指向使用相同解决方案的其他示例,该解决方案也有UPVOLUES。经过测试,链接的代码有效。我只想指出这不是使用NTP。它是使用SNTP。这对我的使用很有用。我只想指出这不是使用NTP。它是使用SNTP。这是usef为我的使用而工作。
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;
    }
}