Jul 22, 2011

Get Local DNS Server Address using C#


using System;
using System.Net;
using System.Net.NetworkInformation;



In this example we will get the DNS server address that is configured on your local network adapter. Start by getting all the Network Interfaces, loop over them to find one which has anOperationalStatus of Up, then get the IPInterfaceProperties of the activeNetworkInterface, then get the DNS Addresses from the IPInterfaceProperties and then return the first value.


private static void GetDnsAdress()
        {
            string strLookNetworkType = "Local Area Connection";
            string strGetNetworkType;
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                strGetNetworkType = networkInterface.Name.ToString();
                if (string.Compare(strLookNetworkType, strGetNetworkType) == 0)
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                        IPAddressCollection dnsAddresses = ipProperties.DnsAddresses;
                        foreach (IPAddress dnsAdress in dnsAddresses)
                        {
                            MessageBox.Show(dnsAdress.ToString());
                        }
                        return;
                    }
                }
            }
        }

No comments:

Post a Comment