Question

I am building a SMTP diagnostics tool by using c# 4.0 If I know the IP Address of Primary NS of a domain, I can get MX,A and CNAME records. So I can validate any email and run legal diagnostics commands. , if I can connect to mail server.

My problem is that I could not find a proper .NET solution to get Primary NS for a given domain.

I know there are some managed clients but I can not add them as reference to my solution or their source code is closed.

What is the differences of managed code and .NET for this issue , that managed code can query NS of a domain and .NET can not as stated here. ?

What is the proper way to implement such a kind of functionality ?

Regards

Was it helpful?

Solution

You can get the IP of your DNS server using IPInterfaceProperties.DnsAddresses. A code example can be found here: http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ipinterfaceproperties.dnsaddresses.aspx

You can then query that server using the component found here: http://www.codeproject.com/Articles/12072/C-NET-DNS-query-component

You can find the primary DNS server by querying for SOA records.

List<IPAddress> dnsServers = new List<IPAddress>();

NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

foreach (NetworkInterface adapter in adapters)
{
    IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
    IPAddressCollection adapterDnsServers = adapterProperties.DnsAddresses;

    if (adapterDnsServers.Count > 0)
        dnsServers.AddRange(adapterDnsServers);
}

foreach (IPAddress dnsServer in (from d in dnsServers 
                                where d.AddressFamily == AddressFamily.InterNetwork
                               select d))
{
    Console.WriteLine("Using server {0}", dnsServer);

    // create a request
    Request request = new Request();

    // add the question
    request.AddQuestion(new Question("stackoverflow.com", DnsType.MX, DnsClass.IN));

    // send the query and collect the response
    Response response = Resolver.Lookup(request, dnsServer);

    // iterate through all the answers and display the output
    foreach (Answer answer in response.Answers)
    {
        MXRecord record = (MXRecord)answer.Record;
        Console.WriteLine("{0} ({1}), preference {2}", record.DomainName, Dns.GetHostAddresses(record.DomainName)[0], record.Preference);
    }

    Console.WriteLine();
}

Console.ReadLine();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top