HttpsReverseProxyPort.cs 1.5 KB

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