应用关闭时恢复原dns记录

This commit is contained in:
陈国伟 2021-06-21 08:50:48 +08:00
parent 922d47fdab
commit 2bdec42b0a
2 changed files with 29 additions and 19 deletions

View File

@ -17,6 +17,7 @@ namespace FastGithub.Dns
private readonly DnsServer dnsServer; private readonly DnsServer dnsServer;
private readonly IOptions<DnsOptions> options; private readonly IOptions<DnsOptions> options;
private readonly ILogger<DnsHostedService> logger; private readonly ILogger<DnsHostedService> logger;
private IPAddress[]? dnsAddresses;
/// <summary> /// <summary>
/// dns后台服务 /// dns后台服务
@ -43,7 +44,7 @@ namespace FastGithub.Dns
{ {
this.dnsServer.Listen(); this.dnsServer.Listen();
this.logger.LogInformation("dns服务启用成功"); this.logger.LogInformation("dns服务启用成功");
this.SetNameServers(IPAddress.Loopback, this.options.Value.UpStream); this.dnsAddresses = this.SetNameServers(IPAddress.Loopback, this.options.Value.UpStream);
return Task.CompletedTask; return Task.CompletedTask;
} }
@ -57,30 +58,38 @@ namespace FastGithub.Dns
{ {
this.dnsServer.Dispose(); this.dnsServer.Dispose();
this.logger.LogInformation("dns服务已终止"); this.logger.LogInformation("dns服务已终止");
this.SetNameServers();
if (this.dnsAddresses != null)
{
this.SetNameServers(this.dnsAddresses);
}
return Task.CompletedTask; return Task.CompletedTask;
} }
/// <summary> /// <summary>
/// 设dns /// 设dns
/// </summary> /// </summary>
/// <param name="nameServers"></param> /// <param name="nameServers"></param>
private void SetNameServers(params IPAddress[] nameServers) /// <returns></returns>
private IPAddress[]? SetNameServers(params IPAddress[] nameServers)
{ {
var action = nameServers.Length == 0 ? "清除" : "设置";
if (this.options.Value.SetToLocalMachine && OperatingSystem.IsWindows()) if (this.options.Value.SetToLocalMachine && OperatingSystem.IsWindows())
{ {
try try
{ {
NameServiceUtil.SetNameServers(nameServers); var results = NameServiceUtil.SetNameServers(nameServers);
this.logger.LogInformation($"{action}本机dns成功"); this.logger.LogInformation($"设置本机dns成功");
return results;
} }
catch (Exception ex) catch (Exception ex)
{ {
this.logger.LogWarning($"{action}本机dns失败{ex.Message}"); this.logger.LogWarning($"设置本机dns失败{ex.Message}");
} }
} }
return default;
} }
} }
} }

View File

@ -32,12 +32,9 @@ namespace FastGithub.Dns
var dwBestIfIndex = 0u; var dwBestIfIndex = 0u;
var dwDestAddr = BitConverter.ToUInt32(remoteAddress.GetAddressBytes()); var dwDestAddr = BitConverter.ToUInt32(remoteAddress.GetAddressBytes());
var errorCode = GetBestInterface(dwDestAddr, ref dwBestIfIndex); var errorCode = GetBestInterface(dwDestAddr, ref dwBestIfIndex);
if (errorCode != 0) return errorCode != 0
{ ? throw new NetworkInformationException(errorCode)
throw new NetworkInformationException(errorCode); : NetworkInterface
}
return NetworkInterface
.GetAllNetworkInterfaces() .GetAllNetworkInterfaces()
.Where(item => item.GetIPProperties().GetIPv4Properties().Index == dwBestIfIndex) .Where(item => item.GetIPProperties().GetIPv4Properties().Index == dwBestIfIndex)
.FirstOrDefault(); .FirstOrDefault();
@ -49,19 +46,23 @@ namespace FastGithub.Dns
/// <param name="nameServers"></param> /// <param name="nameServers"></param>
/// <exception cref="NetworkInformationException"></exception> /// <exception cref="NetworkInformationException"></exception>
/// <exception cref="NotSupportedException"></exception> /// <exception cref="NotSupportedException"></exception>
public static void SetNameServers(params IPAddress[] nameServers) /// <returns>未设置之前的记录</returns>
public static IPAddress[] SetNameServers(params IPAddress[] nameServers)
{ {
var networkIF = GetBestNetworkInterface(www_baidu_com); var networkInterface = GetBestNetworkInterface(www_baidu_com);
if (networkIF == null) if (networkInterface == null)
{ {
throw new NotSupportedException("找不到网络适配器用来设置dns"); throw new NotSupportedException("找不到网络适配器用来设置dns");
} }
var dnsAddresses = networkInterface.GetIPProperties().DnsAddresses.ToArray();
Netsh($@"interface ipv4 delete dns ""{networkIF.Name}"" all"); Netsh($@"interface ipv4 delete dns ""{networkInterface.Name}"" all");
foreach (var address in nameServers) foreach (var address in nameServers)
{ {
Netsh($@"interface ipv4 add dns ""{networkIF.Name}"" {address} validate=no"); Netsh($@"interface ipv4 add dns ""{networkInterface.Name}"" {address} validate=no");
} }
return dnsAddresses;
} }
/// <summary> /// <summary>