I believe the timeout you implemented doesn't work because the method always returns immediately.
The UDP protocol is connectionless. When you call Connect()
on an UDP socket, nothing really happens, you're just setting a default endpoint so you don't repeat yourself on each Send()
call.
The Send()
call also returns pretty quickly, even if the remote host is unreachable. In which case the data would be lost and this is how UDP is meant to work.
The bottom line:
You need to implement a timeout on the Receive()
call:
var result = socket.BeginReceive(ntpData, 0, ntpData.Length, SocketFlags.None, null, null);
var success = result.AsyncWaitHandle.WaitOne(15000);
if (!success)
{
socket.Close();
throw new ApplicationException("Failed to connect to NTP server within 15 seconds");
}