难以连接到ntp时间服务器

时间:2013-10-30 13:22:31

标签: vb.net time

我正在尝试使用以下代码连接到时间服务器并获得时间但却没有运气:

Dim ntpServer As String = "time.windows.com"
Dim ntpData(47) As Byte
Dim addresses = Dns.GetHostEntry(ntpServer).AddressList
Dim EndP As IPEndPoint = New IPEndPoint(addresses(0), 123)

Dim soc As Socket = New Socket(AddressFamily.InterNetwork, _ 
      SocketType.Dgram, ProtocolType.Udp)

soc.Connect(EndP)
soc.Send(ntpData)
soc.Receive(ntpData)

soc.Close()

通过程序追踪我无法通过以下代码行来获取soc.Receive(ntpData)。我究竟做错了什么?

谢谢

1 个答案:

答案 0 :(得分:1)

您需要向服务器提供一些基本信息:

ntpData(0) = 27

ntpData(0)包含一个名为firstByteBits的部分。

在发送数据以查询回复之前,需要先设置此部分。

第一个字节是

 0 1 2 3 4 5 6 7 
+-+-+-+-+-+-+-+-+
|LI | VN  |Mode |
  • LI =跳跃指示符(发送数据中为0)
  • VN =版本号(3,第3位和第4位)
  • 模式=模式(客户端模式= 3,位6和7设置)

00011011 = 27 = 0x1B

可能是更好的NTP服务器。已知time.windows.com:123服务器池 很慢,有时一段时间没有反应,而且准确度低。更好:pool.ntp.org:123(但请阅读poo.ntp.org关于常规使用的内容。)

e.g。 RFC 5905了解更多详情。