Fix AddressInUseException in tests

This commit is contained in:
nicolas.dorier
2020-01-15 00:22:31 +09:00
parent 32a82bbb7c
commit 0fbda9441a

View File

@@ -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