Jason C
Jason C

Reputation: 40315

Determine if SocketException from UdpClient.Receive was caused by a timeout

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.

Upvotes: 1

Views: 1017

Answers (1)

VillageTech
VillageTech

Reputation: 1995

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

Upvotes: 3

Related Questions