ReverseProxyPort.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.NetworkInformation;
  5. namespace FastGithub.Configuration
  6. {
  7. /// <summary>
  8. /// 反向代理端口
  9. /// </summary>
  10. public static class ReverseProxyPort
  11. {
  12. /// <summary>
  13. /// ssh端口
  14. /// </summary>
  15. public static int Ssh { get; }
  16. /// <summary>
  17. /// git端口
  18. /// </summary>
  19. public static int Git { get; }
  20. /// <summary>
  21. /// http端口
  22. /// </summary>
  23. public static int Http { get; }
  24. /// <summary>
  25. /// https端口
  26. /// </summary>
  27. public static int Https { get; }
  28. /// <summary>
  29. /// 反向代理端口
  30. /// </summary>
  31. static ReverseProxyPort()
  32. {
  33. var ports = new TcpListenerPortCollection();
  34. Ssh = ports.GetAvailablePort(22);
  35. Git = ports.GetAvailablePort(9418);
  36. Http = OperatingSystem.IsWindows() ? ports.GetAvailablePort(80) : ports.GetAvailablePort(3880);
  37. Https = OperatingSystem.IsWindows() ? ports.GetAvailablePort(443) : ports.GetAvailablePort(38443);
  38. }
  39. /// <summary>
  40. /// 已监听的tcp端口集合
  41. /// </summary>
  42. private class TcpListenerPortCollection
  43. {
  44. private readonly HashSet<int> tcpPorts = new();
  45. /// <summary>
  46. /// 已监听的tcp端口集合
  47. /// </summary>
  48. public TcpListenerPortCollection()
  49. {
  50. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  51. foreach (var endpoint in tcpListeners)
  52. {
  53. this.tcpPorts.Add(endpoint.Port);
  54. }
  55. }
  56. /// <summary>
  57. /// 获取可用的随机Tcp端口
  58. /// </summary>
  59. /// <param name="minValue"></param>
  60. /// <returns></returns>
  61. public int GetAvailablePort(int minValue)
  62. {
  63. for (var port = minValue; port < IPEndPoint.MaxPort; port++)
  64. {
  65. if (this.tcpPorts.Contains(port) == false)
  66. {
  67. return port;
  68. }
  69. }
  70. throw new FastGithubException("当前无可用的端口");
  71. }
  72. }
  73. }
  74. }