Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#3.5

Find an open port on a machine using C#

4.79/5 (13 votes)
13 Oct 2011CPOL 69.2K  
How to find an open port in a machine using C#.
Include these namespaces in your class:
C#
using System.Net.NetworkInformation;
using System.Net;

The actual method to get the first open port from the system is as follows:
C#
private string GetOpenPort()
{
  int PortStartIndex = 1000;
  int PortEndIndex = 2000;
  IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
  IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
 
  List<int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();
  int unusedPort = 0;

  for (int port = PortStartIndex; port < PortEndIndex; port++)
  {
     if (!usedPorts.Contains(port))
     {
        unusedPort = port;
        break;
     }
  }
  return unusedPort.ToString();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)