diff --git a/BTCPayServer.Tests/Utils.cs b/BTCPayServer.Tests/Utils.cs index 6e23ba1a0..d2eb75757 100644 --- a/BTCPayServer.Tests/Utils.cs +++ b/BTCPayServer.Tests/Utils.cs @@ -10,13 +10,34 @@ namespace BTCPayServer.Tests { public class Utils { + public static int _nextPort = 8001; + public static object _portLock = new object(); + public static int FreeTcpPort() { - TcpListener l = new TcpListener(IPAddress.Loopback, 0); - l.Start(); - int port = ((IPEndPoint)l.LocalEndpoint).Port; - l.Stop(); - return port; + lock (_portLock) + { + using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) + { + while (true) + { + try + { + var port = _nextPort++; + socket.Bind(new IPEndPoint(IPAddress.Loopback, port)); + return port; + } + catch (SocketException) + { + // Retry unless exhausted + if (_nextPort == 65536) + { + throw; + } + } + } + } + } } // http://stackoverflow.com/a/14933880/2061103