NameServiceUtil.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.NetworkInformation;
  6. using System.Runtime.InteropServices;
  7. using System.Runtime.Versioning;
  8. namespace FastGithub.Dns
  9. {
  10. /// <summary>
  11. /// 域名服务工具
  12. /// </summary>
  13. [SupportedOSPlatform("windows")]
  14. static class NameServiceUtil
  15. {
  16. /// <summary>
  17. /// www.baidu.com的ip
  18. /// </summary>
  19. private static readonly IPAddress www_baidu_com = IPAddress.Parse("183.232.231.172");
  20. [DllImport("iphlpapi")]
  21. private static extern int GetBestInterface(uint dwDestAddr, ref uint pdwBestIfIndex);
  22. /// <summary>
  23. /// 通过远程地址查找匹配的网络适接口
  24. /// </summary>
  25. /// <param name="remoteAddress"></param>
  26. /// <returns></returns>
  27. private static NetworkInterface? GetBestNetworkInterface(IPAddress remoteAddress)
  28. {
  29. var dwBestIfIndex = 0u;
  30. var dwDestAddr = BitConverter.ToUInt32(remoteAddress.GetAddressBytes());
  31. var errorCode = GetBestInterface(dwDestAddr, ref dwBestIfIndex);
  32. if (errorCode != 0)
  33. {
  34. throw new NetworkInformationException(errorCode);
  35. }
  36. return NetworkInterface
  37. .GetAllNetworkInterfaces()
  38. .Where(item => item.GetIPProperties().GetIPv4Properties().Index == dwBestIfIndex)
  39. .FirstOrDefault();
  40. }
  41. /// <summary>
  42. /// 设置域名服务
  43. /// </summary>
  44. /// <param name="nameServers"></param>
  45. /// <exception cref="NetworkInformationException"></exception>
  46. /// <exception cref="NotSupportedException"></exception>
  47. public static void SetNameServers(params IPAddress[] nameServers)
  48. {
  49. var networkIF = GetBestNetworkInterface(www_baidu_com);
  50. if (networkIF == null)
  51. {
  52. throw new NotSupportedException("找不到网络适配器用来设置dns");
  53. }
  54. Netsh($@"interface ipv4 delete dns ""{networkIF.Name}"" all");
  55. foreach (var address in nameServers)
  56. {
  57. Netsh($@"interface ipv4 add dns ""{networkIF.Name}"" {address} validate=no");
  58. }
  59. }
  60. /// <summary>
  61. /// 执行Netsh
  62. /// </summary>
  63. /// <param name="arguments"></param>
  64. private static void Netsh(string arguments)
  65. {
  66. var netsh = new ProcessStartInfo
  67. {
  68. FileName = "netsh.exe",
  69. Arguments = arguments,
  70. CreateNoWindow = true,
  71. UseShellExecute = false,
  72. WindowStyle = ProcessWindowStyle.Hidden
  73. };
  74. Process.Start(netsh)?.WaitForExit();
  75. }
  76. }
  77. }