title: C# Socket.SendTo in a loop eventually causes SocketException (depends on the router)
body: <p><br/>
  I am doing some basic Socket messaging.  I have a routine that works well but there is a problem under load.</p>
  
  <p>I'm using UDP to do a connectionless SendTo to basically do a ping-like operation to see if any of my listeners are out there on the LAN.  Ideally I would just use the broadcast address, but Wireless routers don't seem to relay my broadcast.  My work around is to iterate through all IPs on the Subnet and send my data gram to each IP.  The other PCs are listening and if they get the message they will reply and that is how I get Peers to find each other.  Here is the code that is in the loop which sends the data gram to each IP in the subnet.</p>
  
  <pre><code>            string msgStr = "some message here...";
              byte[] sendbuf = Encoding.ASCII.GetBytes(msgStr);
  
              Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
              socket.Blocking = true;
              socket.SendTo(sendbuf, remoteEndPt);
              //socket.Close();
  </code></pre>
  
  <p>This works, but when the Subnet range is large, say 255.255.0.0 (meaning ~60,000 IPs to iterate through) I will eventually get a SocketException with error code "10022", meaning "Invalid Argument".  This tends to happen after ~10,000 or so successful sends then I start to see this error.  Also, the router I use at work handles it and is presumably a high powered router, but the cheap-o one in my lab is the one that produces the error.</p>
  
  <p>If I put in a wait time after catching the SocketException and before resuming the loop it will typically recover but eventually I'll get the error again.  </p>
  
  <p>I think what is happening is that the buffer on the router gets full and I cannot send anymore data.  The higher quality one at work can handle it but the cheap-o one gets bogged down.  Does that sound plausible?</p>
  
  <p>A couple questions:</p>
  
  <p>1) When using SendTo in a connectionless manner, do I need to call Close() on my Socket?  </p>
  
  <p>I've haven't seen any benefit in calling Close(), but when I do call Close() it severely slows down my iteration (I have it commented out above because it does slow things down a lot).  Does this make sense?</p>
  
  <p>2) Is there a way for me to tell I should wait before trying to send more data?  It doesn't seem right to just catch the Exception which I still don't know what the cause of it is.</p>
  
  <p>Thanks, J.</p>