Skip to content

Commit

Permalink
add: 添加DNS客户端 用于在指定SRV地址时可以解析ip
Browse files Browse the repository at this point in the history
  • Loading branch information
zkhssb committed Apr 17, 2023
1 parent 9f409dc commit 066e912
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
1 change: 1 addition & 0 deletions NectarRCON/NectarRCON.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.0.0" />
<PackageReference Include="CoreRCON" Version="5.0.5" />
<PackageReference Include="DnsClient" Version="1.7.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />
<PackageReference Include="WPF-UI" Version="2.0.3" />
Expand Down
39 changes: 38 additions & 1 deletion NectarRCON/Services/RconConnectService.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using CoreRCON;
using DnsClient;
using Microsoft.Extensions.Hosting;
using NectarRCON.Interfaces;
using NectarRCON.Models;
using System;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
Expand Down Expand Up @@ -51,7 +54,7 @@ public async Task ConnectAsync(ServerInformation info)
{
if (IsConnected() && _rconClient != null)
Close();
string address = info.Address;
string address = GetAddress(info.Address);
if (address.ToLower() == "localhost")
address = "127.0.0.1";
string password = string.Empty;
Expand Down Expand Up @@ -80,7 +83,41 @@ public async Task ConnectAsync(ServerInformation info)
{
_connecting = false;
}

static string GetAddress(string host)
{
try
{
string srvAddress = $"_minecraft._tcp.{host}";
var lookup = new LookupClient();
var result = lookup.Query(srvAddress, QueryType.SRV);
var record = result.Answers.SrvRecords().FirstOrDefault();
if (record != null)
{
IPAddress? ipAddress;
if (IPAddress.TryParse(record.Target.Value, out ipAddress))
{
return ipAddress.ToString();
}
else
{
return AQuery(record.Target.Value);
}
}
}
catch (DnsResponseException) { }
return host;
}

static string AQuery(string host)
{
var lookup = new LookupClient();
var result = lookup.Query(host, QueryType.A);
var record = result.Answers.ARecords().FirstOrDefault();
return record?.Address.ToString() ?? host;
}
}

public bool IsConnected()
=> _connected;
public bool IsConnecting()
Expand Down

0 comments on commit 066e912

Please sign in to comment.