3

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

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
thehoten
  • 123
  • 1
  • 9
  • 1
    It's been my experience that time servers can't always connect. You might be better off using a list of servers(google) and pinging each one until you find an active one. – tinstaafl Oct 30 '13 at 13:59
  • What does "No Luck" mean? Is there an error? – Steve Oct 30 '13 at 14:03
  • Nothing appears to happen - but I can never reach soc.Close() – thehoten Oct 30 '13 at 14:06
  • The servers I have been using appear to be active because pinging them was successful – thehoten Oct 30 '13 at 14:11
  • In this [post](http://stackoverflow.com/questions/16878429/sync-internet-time-with-computer/16879398#16879398) is an answer that contains a class written in vb for connecting to time servers. You might be able to find it of some use. – tinstaafl Oct 30 '13 at 14:13
  • Hi, thanks for the link. I've actually seen this before and implemented it. The problem however is that the majority of servers do not appear to user tcp on port 13. Instead I think it's udp on port 123 – thehoten Oct 30 '13 at 14:19

1 Answers1

1

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 |
  • LI = leap indicator (0 in sent data)
  • VN = version number (3, bits 3 and 4 set)
  • Mode = Mode (client mode = 3, bits 6 and 7 set)

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.

Arno
  • 4,994
  • 3
  • 39
  • 63