.Net DNS Lookups

DNS lookups.  Generally a pain and difficult to do in .Net.  The built in Dns class from the System.Net namespace provides a nice way of resolving an IP address or host name via its GetHostEntry() method but if you want to delve a little further into the DNS record then you’re screwed.

As a fan of nuget I thought I would take a browse through its repository and see if anyone had written a nice wrapper class that could help me out.

That’s when I found the ARSoft.Tools.Net project.  It offers a lot more than I was interested in for the particular project I was working on but it was top of the list so I thought I would give it a try.  That’s one of the great things about nuget.  It provides a really nice and simple way for you to safely install and uninstall 3rd party libraries without having to worry about accidentally leaving a dll lying about.

Anyway, to install the package I opened up my Package Manager Console window:

Package Manager Console

Once that had come up I installed the ARSoft.Tools.Net package:

Install ARSoft.Tools.Net library

Once installed I moved over to my class file and included the ARSoft.Tools.Net.Dns namespace into it.

using ARSoft.Tools.Net.Dns;

Then set about creating my wrapper class.  For the purpose of this example I’ve put together a method which looks up a DNS record and looks for a TXT record which matches the one passed into it.  Not very in depth I know but if you’re interested in finding out more then check out the excellent documentation available from the project site.

public static bool LookupDNSTXTRecord(string domain, string expectedTextValue)
{
bool matchFound = false;</code>

DnsMessage dnsMessage = DnsClient.Default.Resolve(domain, RecordType.Txt);
if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) &amp;&amp; (dnsMessage.ReturnCode != ReturnCode.NxDomain)))
{
throw new Exception("DNS request failed");
}
else
{
foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords)
{
// Look for the expected TXT record and if found then all is good
TxtRecord txtRecord = dnsRecord as TxtRecord;
if (txtRecord != null)
{
if (txtRecord.TextData == expectedTextValue)
{
matchFound = true;
break;
}
}
}
}

return matchFound;
}

I hope you find this useful.