65.9K
CodeProject is changing. Read more.
Home

Find an open port on a machine using C#

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (5 votes)

Oct 15, 2011

CPOL
viewsIcon

11369

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.

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();
}