使用Socket状态码判断网络问题

This commit is contained in:
陈国伟 2021-11-26 17:42:26 +08:00
parent 402b7c5f2a
commit f5e7e4c0d0

View File

@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
@ -110,12 +109,12 @@ namespace FastGithub.DomainResolve
addressElapsed = new AddressElapsed(endPoint.Address, stopWatch.Elapsed);
return this.addressElapsedCache.Set(endPoint, addressElapsed, this.normaleElapsedExpiration);
}
catch (Exception)
catch (Exception ex)
{
cancellationToken.ThrowIfCancellationRequested();
addressElapsed = new AddressElapsed(endPoint.Address, TimeSpan.MaxValue);
var expiration = NetworkInterface.GetIsNetworkAvailable() ? this.normaleElapsedExpiration : this.brokeElapsedExpiration;
var expiration = IsLocalNetworkProblem(ex) ? this.brokeElapsedExpiration : this.normaleElapsedExpiration;
return this.addressElapsedCache.Set(endPoint, addressElapsed, expiration);
}
finally
@ -123,5 +122,23 @@ namespace FastGithub.DomainResolve
stopWatch.Stop();
}
}
/// <summary>
/// 是否为本机网络问题
/// </summary>
/// <param name="ex"></param>
/// <returns></returns>
private static bool IsLocalNetworkProblem(Exception ex)
{
if (ex is not SocketException socketException)
{
return false;
}
var code = socketException.SocketErrorCode;
return code == SocketError.NetworkDown ||
code == SocketError.NetworkUnreachable ||
code == SocketError.HostUnreachable;
}
}
}