NetworkHelper.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.NetworkInformation;
  5. using System.Net.Sockets;
  6. namespace TEAMModelOS.SDK.Helper.Network.NetworkHelper
  7. {
  8. public static class NetHelper
  9. {
  10. /// <summary>
  11. /// The ip segment regex
  12. /// </summary>
  13. private const string IPSegmentRegex = @"\d{0,3}";
  14. /// <summary>
  15. /// Gets the ip.
  16. /// </summary>
  17. /// <param name="ipSegment">ip段</param>
  18. /// <returns></returns>
  19. public static string GetIp(string ipSegment)
  20. {
  21. if (string.IsNullOrWhiteSpace(ipSegment))
  22. throw new ArgumentNullException(nameof(ipSegment));
  23. //如果设置的IP支持* 的时候,再去智能的选择ip
  24. if (!ipSegment.Contains("*"))
  25. {
  26. return ipSegment;
  27. }
  28. ipSegment = ipSegment.Replace("*", IPSegmentRegex).Replace(".", "\\.");
  29. var hostAddrs = NetworkInterface.GetAllNetworkInterfaces()
  30. .Where(i => i.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
  31. .SelectMany(i => i.GetIPProperties().UnicastAddresses)
  32. .Select(a => a.Address)
  33. .Where(a => !(a.IsIPv6LinkLocal || a.IsIPv6Multicast || a.IsIPv6SiteLocal || a.IsIPv6Teredo))
  34. .ToList();
  35. foreach (var ip in hostAddrs)
  36. {
  37. if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
  38. && System.Text.RegularExpressions.Regex.IsMatch(ip.ToString(), ipSegment))
  39. {
  40. return ip.ToString();
  41. }
  42. }
  43. throw new Exception($"找不到ipsegement:{ipSegment}匹配的ip, OR No network adapters with an IPv4 address in the system!");
  44. }
  45. /// <summary>
  46. /// 解析ip和port
  47. /// </summary>
  48. /// <param name="serviceAddress"></param>
  49. /// <returns></returns>
  50. public static Tuple<string, int> GetIPAndPort(string serviceAddress)
  51. {
  52. //解析ip
  53. var ipPort = serviceAddress.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
  54. var ip = NetHelper.GetIp(ipPort[0]);
  55. //解析port
  56. var port = 0;
  57. if (ipPort.Length == 2)
  58. {
  59. int.TryParse(ipPort[1], out port);
  60. }
  61. return Tuple.Create(ip, port);
  62. }
  63. /// <summary>
  64. /// 获取所有网卡IP地址
  65. /// </summary>
  66. /// <returns></returns>
  67. public static List<string> getIPAddress()
  68. {
  69. return NetworkInterface.GetAllNetworkInterfaces()
  70. .SelectMany(i => i.GetIPProperties().UnicastAddresses)
  71. .Select(a => a.Address)
  72. //AddressFamily.InterNetwork 过滤掉IPV6 //过滤127.0.0.1 !IPAddress.IsLoopback(a)
  73. .Where(a => a.AddressFamily == AddressFamily.InterNetwork)
  74. .Select(a => a.ToString()).ToList();
  75. }
  76. }
  77. }