Created
April 27, 2019 05:12
-
-
Save yoichiro-manabe/51ef5add180c64acb4adad1a748ebb81 to your computer and use it in GitHub Desktop.
DnsClient.NETを利用したDNSへの問い合わせ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// DNSへの問い合わせクラス | |
/// </summary> | |
public class DnsLookup | |
{ | |
/// <summary> | |
/// DNSへ問い合わせを行いSRVレコードとAレコードからサービスのホストを取得します。 | |
/// </summary> | |
/// <param name="lookupName">問い合わせを行うSRVレコードに対応したNamespace</param> | |
/// <returns><see cref="ServiceHost"/></returns> | |
public async Task<ServiceHost> Execute(string lookupName) | |
{ | |
var client = new LookupClient {UseCache = true}; | |
var result = await client.QueryAsync(lookupName, QueryType.SRV); | |
Console.WriteLine($"result.Header={result.Header}"); | |
if (result.HasError) | |
{ | |
return ServiceHost.Build(); | |
} | |
var srvRecord = result.Answers.OfType<SrvRecord>().FirstOrDefault(); | |
if (srvRecord == null) | |
{ | |
return ServiceHost.Build(); | |
} | |
var aRecordResult = await client.QueryAsync(srvRecord.Target, QueryType.A); | |
var aRecord = aRecordResult.Answers.OfType<ARecord>().FirstOrDefault(); | |
if (aRecord == null) | |
{ | |
return ServiceHost.Build(); | |
} | |
return ServiceHost.Build(aRecord.Address.ToString(), srvRecord.Port); | |
} | |
} | |
public class ServiceHost | |
{ | |
public string IpAddress { get; } | |
public int? Port { get; } | |
private ServiceHost(string ipAddress, int? port) | |
{ | |
IpAddress = ipAddress; | |
Port = port; | |
} | |
public static ServiceHost Build(string ipAddress, int port) | |
{ | |
return new ServiceHost(ipAddress, port); | |
} | |
public static ServiceHost Build() | |
{ | |
return new ServiceHost("", null); | |
} | |
public string BaseUrl() | |
{ | |
if (string.IsNullOrEmpty(IpAddress)) | |
{ | |
return ""; | |
} | |
if (!Port.HasValue) | |
{ | |
return ""; | |
} | |
return $"http://{IpAddress}:{Port}/"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment