• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 270
  • Last Modified:

Get DNS servers (name servers) that is assigned to the machine

Basically, I want to make a DNS query, but first, I need to know which DNS server to use.

The DNS server the machine use is a good choice.

Thanks in advance.
0
pmengal
Asked:
pmengal
  • 2
1 Solution
 
redpipeCommented:

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

public static string[] GetNetworkInterfaces()
    {
      NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
      if (nics == null || nics.Length < 1) {
        throw new Exception("No network interfaces found");
      }

      String[] s = new string[nics.Length];
      int i = 0;
      foreach (NetworkInterface adapter in nics) {
        s[i] = adapter.Description;
        i++;
      }
      return s;
    }

private static string[] GetAdapterIpAdresses(NetworkInterface adapter){
      if (adapter == null) {
        throw new Exception("No network interfaces found");
      }
      IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
      string[] s = null;
      IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
      if (dnsServers != null) {
        s = new string[dnsServers.Count];
        int i = 0;
        foreach (IPAddress dns in dnsServers) {
          s[i] = dns.ToString();
          i++;
        }
      }
      return s;
    }
0
 
cookreCommented:
Note that IPInterfaceProperties.DnsAddresses is only in .NET 2 and 3.

For pre-2.0, you can either run ipconfig and parse its stdout, or walk some rather tortuous, OS specific Registry chains.
0
 
pmengalAuthor Commented:
Brillant!
0
 
redpipeCommented:
Another common way of doing this is through WMI by querying the Win32_NetworkAdapterConfiguration class. I have no experience with this myself, but seen loads of code on it. An ingenious app written by Omar Al Zabir for switching between different network configurations, and written in C# v.1.1 may help you on your way.

SwitchNetConfig - Laptop users, quickly switch network and proxy configuration in different places
http://www.codeproject.com/csharp/oazswitchnetconfig.asp
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now