How to get mx records for a dns name with System.Net.DNS? [closed]

Update 2018/5/23:

Check out MichaC’s answer for a newer library that has .NET standard support.

Original Answer:

The ARSoft.Tools.Net library by Alexander Reinert seems to do the job pretty well.

It’s available from NuGet:

PM> Install-Package ARSoft.Tools.Net

Import the namespace:

using ARSoft.Tools.Net.Dns;

Then making a synchronous lookup is as simple as:

var resolver = new DnsStubResolver();
var records = resolver.Resolve<MxRecord>("gmail.com", RecordType.Mx);
foreach (var record in records) {
    Console.WriteLine(record.ExchangeDomainName?.ToString());
}

Which gives us the output:

gmail-smtp-in.l.google.com.
alt1.gmail-smtp-in.l.google.com.
alt2.gmail-smtp-in.l.google.com.
alt3.gmail-smtp-in.l.google.com.
alt4.gmail-smtp-in.l.google.com.

Underneath the hood, it looks like the library constructs the UDP (or TCP) packets necessary to send to the resolver, like you might expect. The library even has logic (invoked with DnsClient.Default) to discover which DNS server to query.

Full documentation can be found here.

Leave a Comment