NetworkHelper.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using System.Collections.Generic;
  2. using System.Net;
  3. using System.Net.NetworkInformation;
  4. using System.Net.Sockets;
  5. namespace ET
  6. {
  7. public static class NetworkHelper
  8. {
  9. public static string[] GetAddressIPs()
  10. {
  11. List<string> list = new List<string>();
  12. foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
  13. {
  14. if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
  15. {
  16. continue;
  17. }
  18. foreach (UnicastIPAddressInformation add in networkInterface.GetIPProperties().UnicastAddresses)
  19. {
  20. list.Add(add.Address.ToString());
  21. }
  22. }
  23. return list.ToArray();
  24. }
  25. // 优先获取IPV4的地址
  26. public static IPAddress GetHostAddress(string hostName)
  27. {
  28. IPAddress[] ipAddresses = Dns.GetHostAddresses(hostName);
  29. IPAddress returnIpAddress = null;
  30. foreach (IPAddress ipAddress in ipAddresses)
  31. {
  32. returnIpAddress = ipAddress;
  33. if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
  34. {
  35. return ipAddress;
  36. }
  37. }
  38. return returnIpAddress;
  39. }
  40. public static IPEndPoint ToIPEndPoint(string host, int port)
  41. {
  42. return new IPEndPoint(IPAddress.Parse(host), port);
  43. }
  44. public static IPEndPoint ToIPEndPoint(string address)
  45. {
  46. int index = address.LastIndexOf(':');
  47. string host = address.Substring(0, index);
  48. string p = address.Substring(index + 1);
  49. int port = int.Parse(p);
  50. return ToIPEndPoint(host, port);
  51. }
  52. }
  53. }