ReverseProxyPort.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.NetworkInformation;
  5. using System.Net.Sockets;
  6. namespace FastGithub.Configuration
  7. {
  8. /// <summary>
  9. /// 反向代理端口
  10. /// </summary>
  11. public static class ReverseProxyPort
  12. {
  13. /// <summary>
  14. /// ssh端口
  15. /// </summary>
  16. public static int Ssh { get; } = OperatingSystem.IsWindows() ? GetAvailableTcpPort(22) : GetAvailableTcpPort(3822);
  17. /// <summary>
  18. /// http端口
  19. /// </summary>
  20. public static int Http { get; } = OperatingSystem.IsWindows() ? GetAvailableTcpPort(80) : GetAvailableTcpPort(3880);
  21. /// <summary>
  22. /// https端口
  23. /// </summary>
  24. public static int Https { get; } = OperatingSystem.IsWindows() ? GetAvailableTcpPort(443) : GetAvailableTcpPort(38443);
  25. /// <summary>
  26. /// 获取可用的随机Tcp端口
  27. /// </summary>
  28. /// <param name="minValue"></param>
  29. /// <param name="addressFamily"></param>
  30. /// <returns></returns>
  31. private static int GetAvailableTcpPort(int minValue, AddressFamily addressFamily = AddressFamily.InterNetwork)
  32. {
  33. var hashSet = new HashSet<int>();
  34. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  35. foreach (var endpoint in tcpListeners)
  36. {
  37. if (endpoint.AddressFamily == addressFamily)
  38. {
  39. hashSet.Add(endpoint.Port);
  40. }
  41. }
  42. for (var port = minValue; port < IPEndPoint.MaxPort; port++)
  43. {
  44. if (hashSet.Contains(port) == false)
  45. {
  46. return port;
  47. }
  48. }
  49. throw new FastGithubException("当前无可用的端口");
  50. }
  51. }
  52. }