2010-05-25 17 views
10

Come posso ottenere il mio server DNS corrente in C#?Come posso ottenere il mio server DNS corrente in C#?

+2

Con il tuo, intendi il server DNS della macchina locale, i server DNS per il tuo dominio o qualcos'altro? Esistono molte risposte diverse su ciò che è "il tuo server DNS", IMO. –

+0

Sto pensando di convertire il mio codice non sicuro che esegue la ricerca Mx Record in una versione sicura. Vedi: http://stackoverflow.com/questions/2906615/how-to-get-around-dnsrecordlistfree-error-in-net-framework-4-0 –

+0

Quello che mi piacerebbe sapere è come eseguire Ricerche DNS senza dover specificare il nome del server DNS, vale a dire che il sistema utilizza l'impostazione predefinita. Questo è ciò che accade ogni volta che digiti un URL da qualche parte, quindi non sono sicuro del motivo per cui le classi DNS non possono consentire un valore predefinito. –

risposta

0

Recentemente stavo cercando di fare la stessa cosa e ho trovato questo excellent example da Robert Sindal.

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

namespace HowToGetLocalDnsServerAddressConsoleApp 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine(GetDnsAdress()); 
      Console.ReadKey(); 
     } 

     private static IPAddress GetDnsAdress() 
     { 
      NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); 

      foreach (NetworkInterface networkInterface in networkInterfaces) 
      { 
       if (networkInterface.OperationalStatus == OperationalStatus.Up) 
       { 
        IPInterfaceProperties ipProperties = networkInterface.GetIPProperties(); 
        IPAddressCollection dnsAddresses = ipProperties.DnsAddresses; 

        foreach (IPAddress dnsAdress in dnsAddresses) 
        { 
         return dnsAdress; 
        } 
       } 
      } 

      throw new InvalidOperationException("Unable to find DNS Address"); 
     } 
    } 
} 
Problemi correlati