IPAddressService.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. using Microsoft.Extensions.Caching.Memory;
  2. using Microsoft.Extensions.Options;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.NetworkInformation;
  9. using System.Net.Sockets;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace FastGithub.DomainResolve
  13. {
  14. /// <summary>
  15. /// IP服务
  16. /// 域名IP关系缓存10分钟
  17. /// IPEndPoint时延缓存5分钟
  18. /// IPEndPoint连接超时5秒
  19. /// </summary>
  20. sealed class IPAddressService
  21. {
  22. private record DomainAddress(string Domain, IPAddress Address);
  23. private readonly TimeSpan domainAddressExpiration = TimeSpan.FromMinutes(10d);
  24. private readonly IMemoryCache domainAddressCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
  25. private record AddressElapsed(IPAddress Address, TimeSpan Elapsed);
  26. private readonly TimeSpan brokeElapsedExpiration = TimeSpan.FromMinutes(1d);
  27. private readonly TimeSpan normaleElapsedExpiration = TimeSpan.FromMinutes(5d);
  28. private readonly TimeSpan connectTimeout = TimeSpan.FromSeconds(5d);
  29. private readonly IMemoryCache addressElapsedCache = new MemoryCache(Options.Create(new MemoryCacheOptions()));
  30. private readonly DnsClient dnsClient;
  31. /// <summary>
  32. /// IP服务
  33. /// </summary>
  34. /// <param name="dnsClient"></param>
  35. public IPAddressService(DnsClient dnsClient)
  36. {
  37. this.dnsClient = dnsClient;
  38. }
  39. /// <summary>
  40. /// 并行获取可连接的IP
  41. /// </summary>
  42. /// <param name="dnsEndPoint"></param>
  43. /// <param name="oldAddresses"></param>
  44. /// <param name="cancellationToken"></param>
  45. /// <returns></returns>
  46. public async Task<IPAddress[]> GetAddressesAsync(DnsEndPoint dnsEndPoint, IEnumerable<IPAddress> oldAddresses, CancellationToken cancellationToken)
  47. {
  48. var ipEndPoints = new HashSet<IPEndPoint>();
  49. // 历史未过期的IP节点
  50. foreach (var address in oldAddresses)
  51. {
  52. var domainAddress = new DomainAddress(dnsEndPoint.Host, address);
  53. if (this.domainAddressCache.TryGetValue(domainAddress, out _))
  54. {
  55. ipEndPoints.Add(new IPEndPoint(address, dnsEndPoint.Port));
  56. }
  57. }
  58. // 新解析出的IP节点
  59. await foreach (var address in this.dnsClient.ResolveAsync(dnsEndPoint, fastSort: false, cancellationToken))
  60. {
  61. ipEndPoints.Add(new IPEndPoint(address, dnsEndPoint.Port));
  62. var domainAddress = new DomainAddress(dnsEndPoint.Host, address);
  63. this.domainAddressCache.Set(domainAddress, default(object), this.domainAddressExpiration);
  64. }
  65. if (ipEndPoints.Count == 0)
  66. {
  67. return Array.Empty<IPAddress>();
  68. }
  69. var addressElapsedTasks = ipEndPoints.Select(item => this.GetAddressElapsedAsync(item, cancellationToken));
  70. var addressElapseds = await Task.WhenAll(addressElapsedTasks);
  71. return addressElapseds
  72. .Where(item => item.Elapsed < TimeSpan.MaxValue)
  73. .OrderBy(item => item.Elapsed)
  74. .Select(item => item.Address)
  75. .ToArray();
  76. }
  77. /// <summary>
  78. /// 获取IP节点的时延
  79. /// </summary>
  80. /// <param name="endPoint"></param>
  81. /// <param name="cancellationToken"></param>
  82. /// <returns></returns>
  83. private async Task<AddressElapsed> GetAddressElapsedAsync(IPEndPoint endPoint, CancellationToken cancellationToken)
  84. {
  85. if (this.addressElapsedCache.TryGetValue<AddressElapsed>(endPoint, out var addressElapsed))
  86. {
  87. return addressElapsed;
  88. }
  89. var stopWatch = Stopwatch.StartNew();
  90. try
  91. {
  92. using var timeoutTokenSource = new CancellationTokenSource(this.connectTimeout);
  93. using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutTokenSource.Token);
  94. using var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  95. await socket.ConnectAsync(endPoint, linkedTokenSource.Token);
  96. addressElapsed = new AddressElapsed(endPoint.Address, stopWatch.Elapsed);
  97. return this.addressElapsedCache.Set(endPoint, addressElapsed, this.normaleElapsedExpiration);
  98. }
  99. catch (Exception)
  100. {
  101. cancellationToken.ThrowIfCancellationRequested();
  102. addressElapsed = new AddressElapsed(endPoint.Address, TimeSpan.MaxValue);
  103. var expiration = NetworkInterface.GetIsNetworkAvailable() ? this.normaleElapsedExpiration : this.brokeElapsedExpiration;
  104. return this.addressElapsedCache.Set(endPoint, addressElapsed, expiration);
  105. }
  106. finally
  107. {
  108. stopWatch.Stop();
  109. }
  110. }
  111. }
  112. }