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

Segfault picture Segfault · Apr 19, 2010 · Viewed 39k times · Source

Is there any built in method in the .NET library that will return all of the MX records for a given domain? I see how you get CNAMES, but not MX records.

Answer

Michael Kropat picture Michael Kropat · Aug 6, 2014

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.