获取我实际的DNS
本文关键字:DNS 获取 | 更新日期: 2023-09-27 18:04:34
我有这个功能来更改DNS:
/**
* Change dns
*
* @param bool
*/
private void changeDns(bool develop)
{
ManagementClass mClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection mObjCol = mClass.GetInstances();
foreach (ManagementObject mObj in mObjCol)
{
if ((bool) mObj["IPEnabled"])
{
ManagementBaseObject mboDNS = mObj.GetMethodParameters("SetDNSServerSearchOrder");
if (mboDNS != null)
{
if (develop == true)
{
// Set dns
mboDNS["DNSServerSearchOrder"] = this.dnsServer;
// Log info
foreach (String dns in this.dnsServer) {
this.addLog(dns, "DNS servers change to:", Color.Green);
}
}
else
{
// Set dns
mboDNS["DNSServerSearchOrder"] = null;
// Log info
this.addLog("DHCP", "DNS servers change to:", Color.Green);
}
// Change dns
mObj.InvokeMethod("SetDNSServerSearchOrder", mboDNS, null);
}
}
}
}
但现在我需要另一种方式。如何获得win32的dns ?
我从MSDN尝试了这个代码,但它返回了大约10个结果。
答案是:
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in nics)
{
if (ni.OperationalStatus == OperationalStatus.Up)
{
IPAddressCollection ips = ni.GetIPProperties().DnsAddresses;
foreach (System.Net.IPAddress ip in ips)
{
MessageBox.Show(ip.ToString());
}
}
}