Skip to content

Commit

Permalink
增加自定义Host域名
Browse files Browse the repository at this point in the history
  • Loading branch information
Ponderfly committed Apr 7, 2024
1 parent ca636af commit 99c58e6
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 66 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -360,4 +360,5 @@ MigrationBackup/
.ionide/

# Fody - auto-generated XML schema
FodyWeavers.xsd
FodyWeavers.xsd
/src/GoogleTranslateIpCheck/.idea/.idea.GoogleTranslateIpCheck/.idea
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,8 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Flurl.Http" Version="4.0.0-pre3" />
<PackageReference Include="IPNetwork2" Version="2.6.609" >
<Aliases>IPNetwork2</Aliases>
</PackageReference>
<PackageReference Include="Flurl.Http" Version="4.0.2" />
<PackageReference Include="IPNetwork2" Version="3.0.648" />
</ItemGroup>

<ItemGroup>
Expand Down
130 changes: 69 additions & 61 deletions src/GoogleTranslateIpCheck/GoogleTranslateIpCheck/Program.cs
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
extern alias IPNetwork2;
using Flurl.Http;
using Flurl.Http;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;

const string configFile = "config.json";
const string Host = "translate.googleapis.com";
const string Host2 = "translate.google.com";

Console.WriteLine("如果支持IPv6推荐优先使用,使用参数 -6 启动");
var config = new Config();
if (File.Exists(configFile))
{
try
{
var json = File.ReadAllText(configFile);
config = JsonSerializer.Deserialize(json, MyJsonContext.Default.Config);
config = JsonSerializer.Deserialize(json, ConfigJsonContext.Default.Config);
}
catch
{
Expand All @@ -38,11 +35,13 @@
isIPv6 = true;
ipFile = "IPv6.txt";
}

if (args.Any(x => "-y".Equals(x, StringComparison.OrdinalIgnoreCase)))
autoSet = true;
if (args.Any(x => "-s".Equals(x, StringComparison.OrdinalIgnoreCase)))
ips = await ScanIpAsync();
}

ips ??= await ReadIpAsync();
if (ips is null || ips?.Count == 0)
ips = await ScanIpAsync();
Expand All @@ -66,6 +65,7 @@ await Parallel.ForEachAsync(ips!, new ParallelOptions()
Console.ReadKey();
return;
}

Console.WriteLine();
Console.WriteLine("检测IP完毕,按照响应时间排序结果");
Console.WriteLine();
Expand All @@ -81,15 +81,16 @@ await Parallel.ForEachAsync(ips!, new ParallelOptions()
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
Console.WriteLine(@"Host文件路径为 /etc/hosts ");
Console.WriteLine();
Console.WriteLine($"{bestIp} {Host}");
Console.WriteLine($"{bestIp} {Host2}");
foreach (var host in config!.Hosts)
Console.WriteLine($"{bestIp} {host}");
Console.WriteLine();
if (!autoSet)
{
Console.WriteLine("是否设置到Host文件(Y:设置)");
if (Console.ReadKey().Key != ConsoleKey.Y)
return;
}

Console.WriteLine();
try
{
Expand All @@ -101,6 +102,7 @@ await Parallel.ForEachAsync(ips!, new ParallelOptions()
Console.ReadKey();
return;
}

Console.WriteLine("设置成功");
await FlushDns();
if (!autoSet)
Expand Down Expand Up @@ -128,11 +130,13 @@ async Task TestIpAsync(string ip)
flag = true;
}
}

if (flag)
{
Console.WriteLine($"{ip}: 超时");
return;
}

times.TryAdd(ip, time);
Console.WriteLine($"{ip}: 响应时间 {time} ms");
}
Expand All @@ -150,15 +154,15 @@ async Task TestIpAsync(string ip)
var _ips = new ConcurrentBag<string>();
try
{
var ipnetwork = IPNetwork2.System.Net.IPNetwork.Parse(ipRange);
var ipnetwork = IPNetwork2.Parse(ipRange);
await
Parallel.ForEachAsync(
ipnetwork.ListIPAddress(IPNetwork2.System.Net.FilterEnum.Usable),
new ParallelOptions()
{
MaxDegreeOfParallelism = config!.扫描并发数,
CancellationToken = cts.Token
},
ipnetwork.ListIPAddress(FilterEnum.Usable),
new ParallelOptions()
{
MaxDegreeOfParallelism = config!.扫描并发数,
CancellationToken = cts.Token
},
async (ip, ct) =>
{
try
Expand All @@ -171,10 +175,15 @@ async Task TestIpAsync(string ip)
if (listIp.Count + _ips.Count >= config!.IP扫描限制数量)
cts.Cancel();
}
catch { }
catch
{
}
});
}
catch { continue; }
catch
{
continue;
}
finally
{
foreach (var ip in _ips)
Expand All @@ -183,6 +192,7 @@ async Task TestIpAsync(string ip)
}
}
}

Console.WriteLine($"扫描完成,找到 {listIp.Count} 条IP");
return listIp;
}
Expand All @@ -192,7 +202,7 @@ async Task<bool> GetResultAsync(string ip)
var str = !isIPv6 ? $"{ip}" : $"[{ip}]";
var url = $@"https://{str}/translate_a/single?client=gtx&sl=zh-CN&tl=en&dt=t&q=你好";
return (await url
.WithHeader("host", Host)
.WithHeader("host", config!.Hosts[0])
.WithTimeout(config!.扫描超时)
.GetStringAsync()).Contains("Hello");
}
Expand All @@ -218,6 +228,7 @@ async Task<bool> GetResultAsync(string ip)
return null;
}
}

var listIp = new HashSet<string>();
foreach (var line in lines)
{
Expand All @@ -237,6 +248,7 @@ async Task<bool> GetResultAsync(string ip)
listIp.Add(line.Trim());
}
}

Console.WriteLine($"找到 {listIp.Count} 条IP");
return listIp;
}
Expand Down Expand Up @@ -270,36 +282,24 @@ async Task SetHostFileAsync()
else
throw new Exception("暂不支持配置HOST文件");

var ip = $"{bestIp} {Host}";
var ip2 = $"{bestIp} {Host2}";
File.SetAttributes(hostFile, FileAttributes.Normal);
var lines = (await File.ReadAllLinesAsync(hostFile)).ToList();

if (lines.Any(s => s.Contains(Host)))
Update(Host);
else
Add(ip);
if (lines.Any(s => s.Contains(Host2)))
Update(Host2);
else
Add(ip2);
await File.WriteAllLinesAsync(hostFile, lines);
return;

void Update(string host)
foreach (var host in config!.Hosts)
{
for (var i = 0; i < lines!.Count; i++)
var hostLine = $"{bestIp} {host}";
var existingLineIndex = lines.FindIndex(line => line.Contains(host));
if (existingLineIndex >= 0)
{
lines[existingLineIndex] = hostLine;
}
else
{
if (lines[i].Contains(host))
lines[i] = $"{bestIp} {host}";
lines.Add(hostLine);
}
}

void Add(string s)
{
lines.Add(Environment.NewLine);
lines.Add(s);
}
await File.WriteAllLinesAsync(hostFile, lines);
return;
}

async Task SaveIpFileAsync()
Expand Down Expand Up @@ -331,6 +331,7 @@ async Task FlushDns()
{
return;
}

try
{
using var process = new Process()
Expand Down Expand Up @@ -370,6 +371,7 @@ public partial class RegexStuff
{
[GeneratedRegex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$")]
public static partial Regex IpRegex();

[GeneratedRegex(@"^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$")]
public static partial Regex IPv6Regex();
}
Expand All @@ -381,29 +383,35 @@ public class Config
public int IP扫描限制数量 { get; set; } = 5;
public int 扫描超时 { get; set; } = 4;
public int 扫描并发数 { get; set; } = 80;
public string[] Hosts { get; set; } =
"""
translate.googleapis.com
translate.google.com
translate-pa.googleapis.com
""".Split(Environment.NewLine);
public string[] IP段 { get; set; } =
""""
142.250.0.0/15
172.217.0.0/16
172.253.0.0/16
108.177.0.0/17
72.14.192.0/18
74.125.0.0/16
216.58.192.0/19
"""".Split(Environment.NewLine);
""""
142.250.0.0/15
172.217.0.0/16
172.253.0.0/16
108.177.0.0/17
72.14.192.0/18
74.125.0.0/16
216.58.192.0/19
"""".Split(Environment.NewLine);
public string[] IPv6段 { get; set; } =
""""
2404:6800:4008:c15::0/112
2a00:1450:4001:802::0/112
2a00:1450:4001:803::0/112
2a00:1450:4001:809::0/112
2a00:1450:4001:811::0/112
2a00:1450:4001:827::0/112
2a00:1450:4001:828::0/112
"""".Split(Environment.NewLine);
""""
2404:6800:4008:c15::0/112
2a00:1450:4001:802::0/112
2a00:1450:4001:803::0/112
2a00:1450:4001:809::0/112
2a00:1450:4001:811::0/112
2a00:1450:4001:827::0/112
2a00:1450:4001:828::0/112
"""".Split(Environment.NewLine);
}

[JsonSerializable(typeof(Config))]
internal partial class MyJsonContext : JsonSerializerContext
internal partial class ConfigJsonContext : JsonSerializerContext
{
}
}
5 changes: 5 additions & 0 deletions src/GoogleTranslateIpCheck/GoogleTranslateIpCheck/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
"IP扫描限制数量": 5,
"扫描超时": 4,
"扫描并发数": 80,
"Hosts": [
"translate.googleapis.com",
"translate.google.com",
"translate-pa.googleapis.com"
],
"IP段": [
"142.250.0.0/15",
"172.217.0.0/16",
Expand Down

0 comments on commit 99c58e6

Please sign in to comment.