// Connect to the time server and update system time public void Connect(bool UpdateSystemTime, int WaitTime) { messageReceived = false; try { IPEndPoint RemoteIpEndPoint; if (IsCorrectIP(TimeServer)) { IPAddress hostadd = IPAddress.Parse(TimeServer); RemoteIpEndPoint = new IPEndPoint(hostadd, 123); } else { // Resolve server address IPHostEntry hostadd = Dns.GetHostEntry(TimeServer); RemoteIpEndPoint = new IPEndPoint(hostadd.AddressList[0], 123); } //Connect the time server UdpClient TimeSocket = new UdpClient(); UdpState sta = new UdpState(); sta.IP = RemoteIpEndPoint; sta.Socket = TimeSocket; // Initialize data structure Initialize(); TimeSocket.Send(SNTPData, SNTPData.Length, RemoteIpEndPoint); TimeSocket.BeginReceive(new AsyncCallback(ReceiveCallback), sta); // Do some work while we wait for a message. For this example, // we'll just sleep while ((!messageReceived) && (WaitTime > 0)) { Thread.Sleep(100); WaitTime -= 100; } if (!IsResponseValid()) { throw new Exception("Invalid response from " + TimeServer); } DestinationTimestamp = DateTime.Now; } catch (SocketException e) { throw new Exception(e.Message); } // Update system time if (UpdateSystemTime) { SetTime(); } }