如何在C#中获取当前的DNS服务器?
如何在C#中获取当前的DNS服务器?
请参阅MSDN IPInterfaceProperties.DnsAddresses
用于示例代码。
我最近试图做同样的事情并发现了这一点 很好的例子 罗伯特辛达尔。
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");
}
}
}