From 44f23c2ed6040dcc9d5d79d9ce0031aa4547d8b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=9B=BD=E4=BC=9F?= <366193849@qq.com> Date: Thu, 29 Jul 2021 15:14:27 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96hosts=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- FastGithub.Dns/HostsValidator.cs | 86 +++++++++++++++++++++----------- 1 file changed, 57 insertions(+), 29 deletions(-) diff --git a/FastGithub.Dns/HostsValidator.cs b/FastGithub.Dns/HostsValidator.cs index 3ba84f4..31e954a 100644 --- a/FastGithub.Dns/HostsValidator.cs +++ b/FastGithub.Dns/HostsValidator.cs @@ -1,7 +1,7 @@ using FastGithub.Configuration; using Microsoft.Extensions.Logging; using System; -using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Net; @@ -48,45 +48,73 @@ namespace FastGithub.Dns return; } - var lines = await File.ReadAllLinesAsync(hostsPath); - var records = lines.Where(item => item.TrimStart().StartsWith("#") == false); - var localAddresses = GetLocalMachineIPAddress().ToArray(); + var localAddresses = IPGlobalProperties + .GetIPGlobalProperties() + .GetUnicastAddresses() + .Select(item => item.Address) + .ToArray(); - foreach (var record in records) + var lines = await File.ReadAllLinesAsync(hostsPath); + foreach (var line in lines) { + if (HostsRecord.TryParse(line, out var record) == false) + { + continue; + } + if (localAddresses.Contains(record.Address) == true) + { + continue; + } + if (this.fastGithubConfig.IsMatch(record.Domain)) + { + this.logger.LogError($"由于你的hosts文件设置了[{record.Domain}->{record.Address}],{nameof(FastGithub)}无法加速此域名"); + } + } + } + + + /// + /// hosts文件记录 + /// + private class HostsRecord + { + /// + /// 获取域名 + /// + public string Domain { get; } + + /// + /// 获取地址 + /// + public IPAddress Address { get; } + + private HostsRecord(string domain, IPAddress address) + { + this.Domain = domain; + this.Address = address; + } + + public static bool TryParse(string record, [MaybeNullWhen(false)] out HostsRecord value) + { + value = null; + if (record.TrimStart().StartsWith("#")) + { + return false; + } + var items = record.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (items.Length < 2) { - continue; + return false; } if (IPAddress.TryParse(items[0], out var address) == false) { - continue; + return false; } - if (localAddresses.Contains(address)) - { - continue; - } - - var domain = items[1]; - if (this.fastGithubConfig.IsMatch(domain)) - { - this.logger.LogError($"由于你的hosts文件设置了[{domain}->{address}],{nameof(FastGithub)}无法加速此域名"); - } - } - } - - /// - /// 获取本机所有ip - /// - /// - private static IEnumerable GetLocalMachineIPAddress() - { - foreach (var item in IPGlobalProperties.GetIPGlobalProperties().GetUnicastAddresses()) - { - yield return item.Address; + value = new HostsRecord(items[1], address); + return true; } } }