C # Async UDP listener SocketException

I have a pretty simple asynchronous UDP listener, configured as a service, and it has been working pretty well for a while, but recently it crashed into SocketException An existing connection was forcibly closed by the remote host . I have three questions:

  • What causes this? (I did not think UDP sockets have a connection)
  • How can I duplicate it for testing purposes?
  • How can I handle the exception so that everything will work?

My code looks something like this:

 private Socket udpSock; private byte[] buffer; public void Starter(){ //Setup the socket and message buffer udpSock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); udpSock.Bind(new IPEndPoint(IPAddress.Any, 12345)); buffer = new byte[1024]; //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); } private void DoReceiveFrom(IAsyncResult iar){ try{ //Get the received message. Socket recvSock = (Socket)iar.AsyncState; EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0); int msgLen = recvSock.EndReceiveFrom(iar, ref clientEP); byte[] localMsg = new byte[msgLen]; Array.Copy(buffer, localMsg, msgLen); //Start listening for a new message. EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0); udpSock.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock); //Handle the received message Console.WriteLine("Recieved {0} bytes from {1}:{2}", msgLen, ((IPEndPoint)clientEP).Address, ((IPEndPoint)clientEP).Port); //Do other, more interesting, things with the received message. } catch (ObjectDisposedException){ //expected termination exception on a closed socket. // ...I'm open to suggestions on a better way of doing this. } } 

An exception is thrown in the line recvSock.EndReceiveFrom ().

+6
c # asynchronous udp socketexception
source share
2 answers

From this forum topic , it looks like the UDP socket also receives ICMP messages and throws exceptions when they are received. This may be great for low-level status updates, but I found it annoying.

First determine the magic number

 public const int SIO_UDP_CONNRESET = -1744830452; 

Then set the lower io control level to ignore these messages:

 var client = new UdpClient(endpoint); client.Client.IOControl( (IOControlCode)SIO_UDP_CONNRESET, new byte[] { 0, 0, 0, 0 }, null ); 
+13
source share

I saw this error with UDP if the packet was somehow truncated or otherwise not completely delivered. At least I think what is happening. I could never reliably duplicate it.

I would suggest that you catch a SocketException , write it (if you want), and then discard this socket. Then call Starter again:

 catch (SocketException) { // log error udpSock.Close(); Starter(); } 
+2
source share

All Articles