title: UDP client async doesn't close sockets
body: <p>I'm trying to program a custom UDP port sniffer. I'm trying to scan the local network looking for the UDP ports that are receiving data.Maybe this is a really trivial question, but I'm stuck here. I have tried a lot of examples and tutorials but I can't find a good solution. I have done this succesfully, using these two methods:</p>
  
  <pre><code>    private static int udpListenPort = 1026;
  bool flag=false;
  public void ReceiveMessages()
  {
      for (udpListenPort = 1026;  udpListenPort&lt; 1200; udpListenPort++)
      {
          if (flag)
          {
              messageReceived = false;
              IPEndPoint e = new IPEndPoint(IPAddress.Any, udpListenPort);
              UdpClient u = new UdpClient(e);
              UdpState s = new UdpState();
              s.e = e;
              s.u = u;
  
              u.BeginReceive(new AsyncCallback(CheckUdpPort), s);
              for (int i = 0; i &lt; 5; i++)
              {
                  Thread.Sleep(8);
                  if (messageReceived)
                  {
                      break;
                  }
              }
              if (messageReceived)
              {
                  // Updating UI
              }
              //u.Close();    // I'm trying this but returns an exception
              e = null;
              u = null;
              s = null;
  
          }
      }
  }
  </code></pre>
  
  <p>And this:</p>
  
  <pre><code>    public class UdpState
  {
      public IPEndPoint e;
      public UdpClient u;
  }
  private static void CheckUdpPort(IAsyncResult ar)
  {
      UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
      IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
  
      Byte[] data = u.EndReceive(ar, ref e);
  
      // Some code to filter the data received
  
      messageReceived = true;
  
  }
  </code></pre>
  
  <p>I'm using these methods in a WPF program. When the scan finalize and I try to start it again, the IDE retunrs the following exception in this point:</p>
  
  <pre><code>IPEndPoint e = new IPEndPoint(IPAddress.Any, udpListenPort);
              UdpClient u = new UdpClient(e);  //HERE
              UdpState s = new UdpState();
  </code></pre>
  
  <p>System.Net.Sockets.SocketException "Only one usage of each socket address (protocol/network address/port) is normally permitted."</p>
  
  <p>I have tried to close each port, but the program returns the following exception "System.ObjectDisposedException" in this line:</p>
  
  <pre><code>Byte[] data = u.EndReceive(ar, ref e);
  </code></pre>
  
  <p>Any help will be very much appretiated.</p>
  
  <p><strong>Note: After more attempts, I realized that I only have the exception "Only one usage of each socket address (protocol/network address/port) is normally permitted. on the UDP ports that haven't received any data in the previous scan.</strong></p>