端口缓存

This commit is contained in:
陈国伟 2021-11-18 12:51:33 +08:00
parent 6b7450b94f
commit dabdbca566

View File

@ -13,42 +13,64 @@ namespace FastGithub.Configuration
/// <summary> /// <summary>
/// ssh端口 /// ssh端口
/// </summary> /// </summary>
public static int Ssh { get; } = OperatingSystem.IsWindows() ? GetAvailableTcpPort(22) : GetAvailableTcpPort(3822); public static int Ssh { get; }
/// <summary> /// <summary>
/// http端口 /// http端口
/// </summary> /// </summary>
public static int Http { get; } = OperatingSystem.IsWindows() ? GetAvailableTcpPort(80) : GetAvailableTcpPort(3880); public static int Http { get; }
/// <summary> /// <summary>
/// https端口 /// https端口
/// </summary> /// </summary>
public static int Https { get; } = OperatingSystem.IsWindows() ? GetAvailableTcpPort(443) : GetAvailableTcpPort(38443); public static int Https { get; }
/// <summary>
/// 反向代理端口
/// </summary>
static ReverseProxyPort()
{
var ports = new TcpListenerPortCollection();
Ssh = OperatingSystem.IsWindows() ? ports.GetAvailablePort(22) : ports.GetAvailablePort(3822);
Http = OperatingSystem.IsWindows() ? ports.GetAvailablePort(80) : ports.GetAvailablePort(3880);
Https = OperatingSystem.IsWindows() ? ports.GetAvailablePort(443) : ports.GetAvailablePort(38443);
}
/// <summary>
/// 已监听的tcp端口集合
/// </summary>
private class TcpListenerPortCollection
{
private readonly HashSet<int> tcpPorts = new();
/// <summary>
/// 已监听的tcp端口集合
/// </summary>
public TcpListenerPortCollection()
{
var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
foreach (var endpoint in tcpListeners)
{
this.tcpPorts.Add(endpoint.Port);
}
}
/// <summary> /// <summary>
/// 获取可用的随机Tcp端口 /// 获取可用的随机Tcp端口
/// </summary> /// </summary>
/// <param name="minValue"></param> /// <param name="minValue"></param>
/// <returns></returns> /// <returns></returns>
private static int GetAvailableTcpPort(int minValue) public int GetAvailablePort(int minValue)
{ {
var hashSet = new HashSet<int>();
var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
foreach (var endpoint in tcpListeners)
{
hashSet.Add(endpoint.Port);
}
for (var port = minValue; port < IPEndPoint.MaxPort; port++) for (var port = minValue; port < IPEndPoint.MaxPort; port++)
{ {
if (hashSet.Contains(port) == false) if (this.tcpPorts.Contains(port) == false)
{ {
return port; return port;
} }
} }
throw new FastGithubException("当前无可用的端口"); throw new FastGithubException("当前无可用的端口");
} }
} }
} }
}