HttpsReverseProxyPort.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. /// https反向代理端口
  10. /// </summary>
  11. public static class HttpsReverseProxyPort
  12. {
  13. /// <summary>
  14. /// 获取端口值
  15. /// </summary>
  16. public static int Value { get; } = GetAvailableTcpPort(AddressFamily.InterNetwork);
  17. /// <summary>
  18. /// 获取可用的随机Tcp端口
  19. /// </summary>
  20. /// <param name="addressFamily"></param>
  21. /// <returns></returns>
  22. private static int GetAvailableTcpPort(AddressFamily addressFamily)
  23. {
  24. return OperatingSystem.IsWindows()
  25. ? GetAvailableTcpPort(addressFamily, 443)
  26. : GetAvailableTcpPort(addressFamily, 12345);
  27. }
  28. /// <summary>
  29. /// 获取可用的随机Tcp端口
  30. /// </summary>
  31. /// <param name="addressFamily"></param>
  32. /// <param name="min">最小值</param>
  33. /// <returns></returns>
  34. private static int GetAvailableTcpPort(AddressFamily addressFamily, int min)
  35. {
  36. var hashSet = new HashSet<int>();
  37. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  38. foreach (var endpoint in tcpListeners)
  39. {
  40. if (endpoint.AddressFamily == addressFamily)
  41. {
  42. hashSet.Add(endpoint.Port);
  43. }
  44. }
  45. for (var port = min; port < IPEndPoint.MaxPort; port++)
  46. {
  47. if (hashSet.Contains(port) == false)
  48. {
  49. return port;
  50. }
  51. }
  52. throw new FastGithubException("当前无可用的端口");
  53. }
  54. }
  55. }