title: Check if a port is open
body: <p>I can't seem to find anything that tells me if a port in my router is open or not.
  Is this even possible?</p>
  
  <p>The code I have right now doesn't really seem to work...</p>
  
  <pre><code>private void ScanPort()
  {
      string hostname = "localhost";
      int portno = 9081;
      IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];
      try
      {
          System.Net.Sockets.Socket sock =
                  new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                                System.Net.Sockets.SocketType.Stream,
                                                System.Net.Sockets.ProtocolType.Tcp);
          sock.Connect(ipa, portno);
          if (sock.Connected == true) // Port is in use and connection is successful
              MessageBox.Show("Port is Closed");
          sock.Close();
      }
      catch (System.Net.Sockets.SocketException ex)
      {
          if (ex.ErrorCode == 10061) // Port is unused and could not establish connection 
              MessageBox.Show("Port is Open!");
          else
              MessageBox.Show(ex.Message);
      }
  }
  </code></pre>