Skip to content

Instantly share code, notes, and snippets.

@rqx110
Forked from jrusbatch/AvailablePorts.cs
Created February 14, 2023 08:30
Show Gist options
  • Save rqx110/ad76b8486009982f0059e189c4d199a0 to your computer and use it in GitHub Desktop.
Save rqx110/ad76b8486009982f0059e189c4d199a0 to your computer and use it in GitHub Desktop.
Find an Available Port with C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.Net;
namespace AvailablePort
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetAvailablePort(1000).ToString());
Console.ReadLine();
}
/// <summary>
/// checks for used ports and retrieves the first free port
/// </summary>
/// <returns>the free port or 0 if it did not find a free port</returns>
public static int GetAvailablePort(int startingPort)
{
IPEndPoint[] endPoints;
List<int> portArray = new List<int>();
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
//getting active connections
TcpConnectionInformation[] connections = properties.GetActiveTcpConnections();
portArray.AddRange(from n in connections
where n.LocalEndPoint.Port >= startingPort
select n.LocalEndPoint.Port);
//getting active tcp listners - WCF service listening in tcp
endPoints = properties.GetActiveTcpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
//getting active udp listeners
endPoints = properties.GetActiveUdpListeners();
portArray.AddRange(from n in endPoints
where n.Port >= startingPort
select n.Port);
portArray.Sort();
for (int i = startingPort; i < UInt16.MaxValue; i++)
if (!portArray.Contains(i))
return i;
return 0;
}
}
}
@rqx110
Copy link
Author

rqx110 commented Feb 14, 2023

int port = startPort;

        // Try ports until available port is found
        while (IPGlobalProperties
            .GetIPGlobalProperties()
            .GetActiveTcpListeners()
            .Any(x => x.Port == port))
        {
            if (port > port + portRange)
            {
                throw new SystemException($"Couldn't find open port within range {port - portRange} - {port}.");
            }

            port++;
        }

@rqx110
Copy link
Author

rqx110 commented Feb 14, 2023

public static class IpUtilities
{
    private const ushort MIN_PORT = 1;
    private const ushort MAX_PORT = UInt16.MaxValue;
    public static int? GetAvailablePort(ushort lowerPort = MIN_PORT, ushort upperPort = MAX_PORT)
    {
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        var usedPorts = Enumerable.Empty<int>()
            .Concat(ipProperties.GetActiveTcpConnections().Select(c => c.LocalEndPoint.Port))
            .Concat(ipProperties.GetActiveTcpListeners().Select(l => l.Port))
            .Concat(ipProperties.GetActiveUdpListeners().Select(l => l.Port))
            .ToHashSet();
        for (int port = lowerPort; port <= upperPort; port++)
        {
            if (!usedPorts.Contains(port)) return port;
        }
        return null;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment