title: How can I restart a TcpListener without a blocking port?
body: <p>I have a Receiver that uses TcpListener to receive messages. This includes the option to set an auto-restart on the Receiver, in case something causes it to lock up. The problem that I am having is that during the restart, the port is not being released after closing the listener. I know that Windows can keep the port open for 3 to 4 minutes, so I continue checking for five minutes before giving up. Sometimes, though, the port is never released, and the Receiver stops.</p>
  
  <p>Does anyone know how I can shut down a TcpListener, and then immediately open a new one using the same port?</p>
  
  <p>I've included a few snippets of code below:</p>
  
  <p>Create the listener</p>
  
  <pre><code>server = new TcpListener(IPAddress.Any, Port);
  server.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
  server.Start();
  ...
  server.BeginAcceptTcpClient(new AsyncCallback(AcceptMessage), server);
  </code></pre>
  
  <p>Stop the listener</p>
  
  <pre><code>finally
  {
      if (server != null)
          server.Stop();
      server = null;
      ...
  </code></pre>
  
  <p>Restart code</p>
  
  <pre><code>Stop();    
  //  Check to make sure the port is released
  bool isPortInUse = true;
  int count = 0;
  
  //  End when the port is no longer in use, or after 5 minutes
  while (isPortInUse &amp;&amp; count++ &lt; 300)
  {
      bool isAvailable = true;
      IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
      TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
  
      foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
      {
          if (tcpi.LocalEndPoint.Port == Port)
          {
              isAvailable = false;
              break;
          }
      }
      if (isAvailable)
          isPortInUse = false;
      else
          System.Threading.Thread.Sleep(1000);    //  Wait one second
  }
  
  if (!isPortInUse)
  Start();
  </code></pre>