Click here to Skip to main content
15,883,904 members
Articles / Programming Languages / C# 3.5
Alternative
Tip/Trick

Find an open port on a machine using C#

Rate me:
Please Sign up or sign in to vote.
4.00/5 (5 votes)
15 Oct 2011CPOL 11K   1   1
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)


Written By
Student
Wales Wales
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 1 copy paste Pin
Emanuel DSouza28-Feb-12 19:48
Emanuel DSouza28-Feb-12 19:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.