Avoid port conflicts for HttpSys Internal/#1795 (#7808)

This commit is contained in:
Chris Ross 2019-02-28 10:31:15 -08:00 committed by GitHub
parent e7b00a5508
commit f168835c0a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 1 deletions

View File

@ -1,4 +1,4 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
@ -56,5 +56,34 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.Common
}
}
}
private const int BasePort = 5001;
private const int MaxPort = 8000;
private static int NextPort = BasePort;
// GetNextPort doesn't check for HttpSys urlacls.
public static int GetNextHttpSysPort(string scheme)
{
while (NextPort < MaxPort)
{
var port = NextPort++;
using (var server = new HttpListener())
{
server.Prefixes.Add($"{scheme}://localhost:{port}/");
try
{
server.Start();
server.Stop();
return port;
}
catch (HttpListenerException)
{
}
}
}
NextPort = BasePort;
throw new Exception("Failed to locate a free port.");
}
}
}

View File

@ -32,6 +32,10 @@ namespace Microsoft.AspNetCore.Server.IntegrationTesting.Common
// it should provide a hint URL with "localhost" (IPv4 and IPv6) or "[::1]" (IPv6-only).
return new UriBuilder(scheme, "127.0.0.1", 0).Uri;
}
else if (serverType == ServerType.HttpSys)
{
return new UriBuilder(scheme, "localhost", TestPortHelper.GetNextHttpSysPort(scheme)).Uri;
}
else
{
// If the server type is not Kestrel, or status messages are disabled, there is no status message