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.00/5 (5 votes)
15 Oct 2011CPOL 11.3K  
The tcpEndPoints array has duplicates and members outside the required range. It may be better to restrict the array members to the required range, sort them, and remove the duplicates. The first free port can then be found by finding the first non-sequential value.using...

The tcpEndPoints array has duplicates and members outside the required range. It may be better to restrict the array members to the required range, sort them, and remove the duplicates. The first free port can then be found by finding the first non-sequential value.


C#
using System.Collections.Generic;
using System.Linq; 
using System.Net;
using System.Net.NetworkInformation;

private string GetOpenPort()
{
    const int PortStartIndex = 1000;
    const int PortEndIndex = 2000;
    IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
    IEnumerable<int> query =
          (from n in tcpEndPoints.OrderBy(n => n.Port)
          where (n.Port >= PortStartIndex) && (n.Port <= PortEndIndex)
          select n.Port).ToArray().Distinct();

    int i = PortStartIndex;
    foreach (int p in query)
    {
        if (p != i)
        {
            break;
        }
        i++;
    }
    return i > PortEndIndex ? "0": i.ToString();
}

License

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