0

I just started working with the UDPClient in .Net(Core 2). and noticed that upon receive, it can actually throw a "remote has closed connection" exception. This doesn't make much sense to me since UDP does not care for remotes.

I receive UDP Data from an application i have no control over. What i do in short is this:

if(MyUDPClient.Available > 0)
{
    IPEndPoint Point = null;
    Byte[] Data = MyUDPClient.Receive(ref point);
    //[do something with data]
}

However during the lifetime of said application(while i receive Data, above is done in a loop), the call to Receive can throw the exception that the remote has closed the connection(which it didn't...).

Can someon explain to me why this exception is even a thing and maybe even a workaround? All i want is receive Data and identify from which endpoint it orriginated.

Alexander B.
  • 120
  • 1
  • 9
  • Please provide a minimum code sample. Without seeing how you initialize MyUDPClient, we can only speculate what the problem is. It may be that you constructed MyUDPClient with the default constructor, which means that you didn't provide the local port/local endpoint. If this is the case, MyUDPClient.Available will fail because it doesn't know where to look for available data. But you are right, the exception that the remote has closed the connection is very misleading. It probably only means that your UDPClient is not bound to a local port. – Xaver Dec 12 '17 at 19:58
  • after some digging, if found out, that UDP Sockets throw this error after you've tried to send data to an endpoint that closed its socket. While your UDPSocket might have some Data to read, it'll throw an exception because last send did not succeed. A Control-Flag allows you to ignore this. I'll add an answer. – Alexander B. Dec 14 '17 at 17:12

1 Answers1

0

After some digging into it a bit deeper, i found another answere here on stackoverflow which explains it. Source Answer
In short: When a UDPClient.Send fails, because the remote closed its socket, the next Receive(even if there is Data, that's why available > 0) will trigger the exception. There is a Controlflag to set, which allows to ignore this. After all, i don't care about the remote so i don't care about the "unreachable" response from the remotemachine.

var udpClient = new UdpClient();
uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
Alexander B.
  • 120
  • 1
  • 9