Skip to content

Instantly share code, notes, and snippets.

@jrgcubano
Created November 8, 2022 08:51
Show Gist options
  • Save jrgcubano/96a4a8ddd4f16d23642c841a3e321f58 to your computer and use it in GitHub Desktop.
Save jrgcubano/96a4a8ddd4f16d23642c841a3e321f58 to your computer and use it in GitHub Desktop.
PortFinder
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace Ylp.ExampleTests.Fixtures;
public static class PortFinder
{
static readonly List<int> UsedPorts = new();
static readonly object SyncRoot = new();
public static int Next(int minValue = 9000, int maxValue = 15000)
{
lock (SyncRoot)
{
for (var port = minValue; port <= maxValue; port++)
{
if (UsedPorts.Contains(port) || !IsPortAvailable(port))
continue;
UsedPorts.Add(port);
return port;
}
}
throw new Exception($"No available ports in range {minValue} - {maxValue}");
}
static bool IsPortAvailable(int port)
{
try
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Loopback, port));
return true;
}
catch
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment