Reputation: 123
I am trying to use the following piece of code to connect to a time server and attain the time but have had no luck:
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()
Tracing through the program I can't get past the following line of code soc.Receive(ntpData). What am I doing wrong?
Thanks
Upvotes: 3
Views: 1267
Reputation: 5194
you need to provide some basic information to the server:
ntpData(0) = 27
ntpData(0) contains a section called firstByteBits
.
This section needs to be set before sending the data to query for a reply.
First byte is
0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
|LI | VN |Mode |
00011011 = 27 = 0x1B
And possibly a better NTP server. The time.windows.com:123
server pool is known to
be slow, sometimes not responding for a while, and of low accuracy. Better: pool.ntp.org:123
(but please read what's written on poo.ntp.org about regular use).
e.g. RFC 5905 for more details.
Upvotes: 1