1

I have a UdpClient receiving data with a timeout set, e.g.:

UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, 12345));
client.Client.ReceiveTimeout = 5000;     // 5 second timeout

while (!shutdown) {
    IPEndPoint source = null;
    byte[] data = client.Receive(ref source);  
}

Receive is documented as throwing a SocketException if "an error occurred when accessing the socket". The behavior of setting ReceiveTimeout is also documented as throwing a SocketException if the synchronous operation times out.

If I get a SocketException from Receive when a timeout is set, how can I determine if the exception was caused by a timeout rather than a more serious error?

I did confirm that the exception thrown on timeout is an actual SocketException and not some specific subclass of it. The only thing I can really think of is checking the exception message, which is a hack that I'm not really excited about.

Jason C
  • 38,729
  • 14
  • 126
  • 182

1 Answers1

3

You need to examine SocketException.ErrorCode property for value 10060 (WSATIMEDOUT).

The complete list of ErrorCode values you can find here: https://learn.microsoft.com/windows/win32/winsock/windows-sockets-error-codes-2

VillageTech
  • 1,968
  • 8
  • 18