DnsConfig.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Net;
  3. using System.Net.NetworkInformation;
  4. namespace FastGithub.Configuration
  5. {
  6. /// <summary>
  7. /// dns配置
  8. /// </summary>
  9. public class DnsConfig
  10. {
  11. /// <summary>
  12. /// IP地址
  13. /// </summary>
  14. [AllowNull]
  15. public string IPAddress { get; set; }
  16. /// <summary>
  17. /// 端口
  18. /// </summary>
  19. public int Port { get; set; } = 53;
  20. /// <summary>
  21. /// 转换为IPEndPoint
  22. /// </summary>
  23. /// <returns></returns>
  24. /// <exception cref="FastGithubException"></exception>
  25. public IPEndPoint ToIPEndPoint()
  26. {
  27. if (System.Net.IPAddress.TryParse(this.IPAddress, out var address) == false)
  28. {
  29. throw new FastGithubException($"无效的ip:{this.IPAddress}");
  30. }
  31. if (this.Port == 53 && IsLocalMachineIPAddress(address))
  32. {
  33. throw new FastGithubException($"配置的dns值不能指向{nameof(FastGithub)}自身:{this.IPAddress}:{this.Port}");
  34. }
  35. return new IPEndPoint(address, this.Port);
  36. }
  37. public override string ToString()
  38. {
  39. return $"{this.IPAddress}:{this.Port}";
  40. }
  41. /// <summary>
  42. /// 是否为本机ip
  43. /// </summary>
  44. /// <param name="address"></param>
  45. /// <returns></returns>
  46. private static bool IsLocalMachineIPAddress(IPAddress address)
  47. {
  48. foreach (var @interface in NetworkInterface.GetAllNetworkInterfaces())
  49. {
  50. foreach (var addressInfo in @interface.GetIPProperties().UnicastAddresses)
  51. {
  52. if (addressInfo.Address.Equals(address))
  53. {
  54. return true;
  55. }
  56. }
  57. }
  58. return false;
  59. }
  60. }
  61. }