Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Find an open port on a machine using C#

, 15 Oct 2011
Rate this:
Please Sign up or sign in to vote.
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();
}

License

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

About the Author

George Swan
Student
Wales Wales
No Biography provided

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 15 Oct 2011
Article Copyright 2011 by George Swan
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid