Fix races on port acquisition in AddressRegistrationTests (#1520).
This commit is contained in:
parent
0f28c49c5e
commit
47f1db20e0
|
|
@ -505,32 +505,17 @@ namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private static int _nextPort = 8001;
|
|
||||||
private static object _portLock = new object();
|
|
||||||
private static int GetNextPort()
|
private static int GetNextPort()
|
||||||
{
|
{
|
||||||
lock (_portLock)
|
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
|
||||||
{
|
{
|
||||||
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
|
// Let the OS assign the next available port. Unless we cycle through all ports
|
||||||
{
|
// on a test run, the OS will always increment the port number when making these calls.
|
||||||
while (true)
|
// This prevents races in parallel test runs where a test is already bound to
|
||||||
{
|
// a given port, and a new test is able to bind to the same port due to port
|
||||||
try
|
// reuse being enabled by default by the OS.
|
||||||
{
|
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
|
||||||
var port = _nextPort++;
|
return ((IPEndPoint)socket.LocalEndPoint).Port;
|
||||||
socket.Bind(new IPEndPoint(IPAddress.Loopback, port));
|
|
||||||
return port;
|
|
||||||
}
|
|
||||||
catch (SocketException)
|
|
||||||
{
|
|
||||||
// Retry unless exhausted
|
|
||||||
if (_nextPort == 65536)
|
|
||||||
{
|
|
||||||
throw;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue