small refactor of RandomPortFinder

This commit is contained in:
TomPallister 2020-03-11 19:52:24 +00:00
parent c91c99ca72
commit d032774aa0

View File

@ -1,41 +1,47 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
namespace Ocelot.AcceptanceTests
namespace Ocelot.AcceptanceTests
{
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Net;
using System.Net.Sockets;
public static class RandomPortFinder
{
private static readonly int TrialNumber = 100;
private static readonly int BeginPortRange = 20000;
private static readonly int EndPortRange = 45000;
private static Random random = new Random();
private static ConcurrentBag<int> usedPorts = new ConcurrentBag<int>();
private const int TrialNumber = 100;
private const int BeginPortRange = 20000;
private const int EndPortRange = 45000;
private static readonly Random Random = new Random();
private static readonly ConcurrentBag<int> UsedPorts = new ConcurrentBag<int>();
public static int GetRandomPort()
{
int randomPort = 0;
for (int i = 0; i < TrialNumber; i++)
for (var i = 0; i < TrialNumber; i++)
{
randomPort = random.Next(BeginPortRange, EndPortRange);
if (usedPorts.Any(p => p == randomPort))
{
continue;
}
else
{
usedPorts.Add(randomPort);
}
var randomPort = Random.Next(BeginPortRange, EndPortRange);
if (!PortInUse(randomPort))
{
try
{
IPEndPoint ipe = new IPEndPoint(IPAddress.Loopback, randomPort);
return UsePort(randomPort);
}
catch (Exception)
{
// ignored
}
}
}
throw new Exception("Cannot find available port to bind to.");
}
private static int UsePort(int randomPort)
{
UsedPorts.Add(randomPort);
var ipe = new IPEndPoint(IPAddress.Loopback, randomPort);
using (var socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(ipe);
@ -43,13 +49,10 @@ namespace Ocelot.AcceptanceTests
return randomPort;
}
}
catch (Exception)
{
continue;
}
}
throw new Exception("Cannot find available port to bind to.");
private static bool PortInUse(int randomPort)
{
return UsedPorts.Any(p => p == randomPort);
}
}
}