LocalMachine.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Net.NetworkInformation;
  4. using System.Net.Sockets;
  5. namespace FastGithub.Configuration
  6. {
  7. /// <summary>
  8. /// 提供本机设备信息
  9. /// </summary>
  10. public static class LocalMachine
  11. {
  12. /// <summary>
  13. /// 获取可用的随机Tcp端口
  14. /// </summary>
  15. /// <param name="addressFamily"></param>
  16. /// <param name="min">最小值</param>
  17. /// <returns></returns>
  18. public static int GetAvailableTcpPort(AddressFamily addressFamily, int min = 1025)
  19. {
  20. var hashSet = new HashSet<int>();
  21. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  22. foreach (var item in tcpListeners)
  23. {
  24. if (item.AddressFamily == addressFamily)
  25. {
  26. hashSet.Add(item.Port);
  27. }
  28. }
  29. for (var port = min; port < ushort.MaxValue; port++)
  30. {
  31. if (hashSet.Contains(port) == false)
  32. {
  33. return port;
  34. }
  35. }
  36. throw new FastGithubException("当前无可用的端口");
  37. }
  38. /// <summary>
  39. /// 获取可用的随机端口
  40. /// </summary>
  41. /// <param name="addressFamily"></param>
  42. /// <param name="min">最小值</param>
  43. /// <returns></returns>
  44. public static int GetAvailablePort(AddressFamily addressFamily, int min = 1025)
  45. {
  46. var hashSet = new HashSet<int>();
  47. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  48. var udpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
  49. foreach (var item in tcpListeners)
  50. {
  51. if (item.AddressFamily == addressFamily)
  52. {
  53. hashSet.Add(item.Port);
  54. }
  55. }
  56. foreach (var item in udpListeners)
  57. {
  58. if (item.AddressFamily == addressFamily)
  59. {
  60. hashSet.Add(item.Port);
  61. }
  62. }
  63. for (var port = min; port < ushort.MaxValue; port++)
  64. {
  65. if (hashSet.Contains(port) == false)
  66. {
  67. return port;
  68. }
  69. }
  70. throw new FastGithubException("当前无可用的端口");
  71. }
  72. /// <summary>
  73. /// 是否可以监听指定tcp端口
  74. /// </summary>
  75. /// <param name="port"></param>
  76. /// <returns></returns>
  77. public static bool CanListenTcp(int port)
  78. {
  79. var tcpListeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
  80. return tcpListeners.Any(item => item.Port == port) == false;
  81. }
  82. }
  83. }