Read DNS entries with .NET
.NET does not have a built-in mechanism for querying DNS records; nevertheless, this is a use case that is required relatively often.
With the help of the NuGet package DnsClient (Apache License), however, handling the query is very simple:
using DnsClient;
using DnsClient.Protocol;
string domain = "schwabencode.com";
LookupClient lookup = new();
// Helper to perform and display a query
async Task QueryAndPrint(QueryType type)
{
Console.WriteLine($"\n=== {type} Records ===");
IDnsQueryResponse result = await lookup.QueryAsync(domain, type);
foreach (DnsResourceRecord? dnsRecord in result.AllRecords)
{
switch (dnsRecord)
{
case ARecord a:
Console.WriteLine($"A: {a.Address} (TTL: {a.InitialTimeToLive}s)");
break;
case AaaaRecord aaaa:
Console.WriteLine($"AAAA: {aaaa.Address} (TTL: {aaaa.InitialTimeToLive}s)");
break;
case CNameRecord cname:
Console.WriteLine($"CNAME: {cname.CanonicalName} (TTL: {cname.InitialTimeToLive}s)");
break;
case MxRecord mx:
Console.WriteLine($"MX: {mx.Exchange} (Pref: {mx.Preference}, TTL: {mx.InitialTimeToLive}s)");
break;
case NsRecord ns:
Console.WriteLine($"NS: {ns.NSDName} (TTL: {ns.InitialTimeToLive}s)");
break;
case TxtRecord txt:
Console.WriteLine($"TXT: {string.Join(" ", txt.Text)} (TTL: {txt.InitialTimeToLive}s)");
break;
default:
Console.WriteLine($"{dnsRecord}");
break;
}
}
}
// Query each type
await QueryAndPrint(QueryType.A);
await QueryAndPrint(QueryType.AAAA);
await QueryAndPrint(QueryType.CNAME);
await QueryAndPrint(QueryType.MX);
await QueryAndPrint(QueryType.NS);
await QueryAndPrint(QueryType.TXT);
Conclusion
With just a few lines of C# and the powerful DnsClient.NET library, you can build a versatile DNS lookup tool. Whether you're troubleshooting, monitoring, or integrating into larger applications, this console app gives you a solid foundation.
Feel free to experiment, extend, and customize it to fit your needs!