端口缓存

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>
/// 获取可用的随机Tcp端口 /// 反向代理端口
/// </summary> /// </summary>
/// <param name="minValue"></param> static ReverseProxyPort()
/// <returns></returns>
private static int GetAvailableTcpPort(int minValue)
{ {
var hashSet = new HashSet<int>(); var ports = new TcpListenerPortCollection();
var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners(); 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);
}
foreach (var endpoint in tcpListeners) /// <summary>
{ /// 已监听的tcp端口集合
hashSet.Add(endpoint.Port); /// </summary>
} private class TcpListenerPortCollection
{
private readonly HashSet<int> tcpPorts = new();
for (var port = minValue; port < IPEndPoint.MaxPort; port++) /// <summary>
/// 已监听的tcp端口集合
/// </summary>
public TcpListenerPortCollection()
{ {
if (hashSet.Contains(port) == false) var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
foreach (var endpoint in tcpListeners)
{ {
return port; this.tcpPorts.Add(endpoint.Port);
} }
} }
throw new FastGithubException("当前无可用的端口"); /// <summary>
/// 获取可用的随机Tcp端口
/// </summary>
/// <param name="minValue"></param>
/// <returns></returns>
public int GetAvailablePort(int minValue)
{
for (var port = minValue; port < IPEndPoint.MaxPort; port++)
{
if (this.tcpPorts.Contains(port) == false)
{
return port;
}
}
throw new FastGithubException("当前无可用的端口");
}
} }
} }
} }