Created
November 8, 2022 08:51
-
-
Save jrgcubano/96a4a8ddd4f16d23642c841a3e321f58 to your computer and use it in GitHub Desktop.
PortFinder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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