NetworkHelper.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.NetworkInformation;
  5. using System.Net.Sockets;
  6. using System.Runtime.InteropServices;
  7. namespace ET
  8. {
  9. public static class NetworkHelper
  10. {
  11. public static string[] GetAddressIPs()
  12. {
  13. List<string> list = new List<string>();
  14. foreach (NetworkInterface networkInterface in NetworkInterface.GetAllNetworkInterfaces())
  15. {
  16. if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
  17. {
  18. continue;
  19. }
  20. foreach (UnicastIPAddressInformation add in networkInterface.GetIPProperties().UnicastAddresses)
  21. {
  22. list.Add(add.Address.ToString());
  23. }
  24. }
  25. return list.ToArray();
  26. }
  27. // 优先获取IPV4的地址
  28. public static IPAddress GetHostAddress(string hostName)
  29. {
  30. IPAddress[] ipAddresses = Dns.GetHostAddresses(hostName);
  31. IPAddress returnIpAddress = null;
  32. foreach (IPAddress ipAddress in ipAddresses)
  33. {
  34. returnIpAddress = ipAddress;
  35. if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
  36. {
  37. return ipAddress;
  38. }
  39. }
  40. return returnIpAddress;
  41. }
  42. public static IPEndPoint ToIPEndPoint(string host, int port)
  43. {
  44. return new IPEndPoint(IPAddress.Parse(host), port);
  45. }
  46. public static IPEndPoint ToIPEndPoint(string address)
  47. {
  48. int index = address.LastIndexOf(':');
  49. string host = address.Substring(0, index);
  50. string p = address.Substring(index + 1);
  51. int port = int.Parse(p);
  52. return ToIPEndPoint(host, port);
  53. }
  54. public static void SetSioUdpConnReset(Socket socket)
  55. {
  56. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  57. {
  58. return;
  59. }
  60. const uint IOC_IN = 0x80000000;
  61. const uint IOC_VENDOR = 0x18000000;
  62. const int SIO_UDP_CONNRESET = unchecked((int)(IOC_IN | IOC_VENDOR | 12));
  63. socket.IOControl(SIO_UDP_CONNRESET, new[] { Convert.ToByte(false) }, null);
  64. }
  65. }
  66. }