我正在尝试检测 2 个网络适配器的 DNS 更改。
我在 win 7 64 位机器上使用 c# .net 4.0。
监听网络适配器win注册表项的代码(在RegisterToDNSChanges里面):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.NetworkInformation;
using System.Management;
using System.Threading;
namespace CheckDNS
{
class NetworkAdapterInfo
{
private Dictionary<NetworkInterface, IPAddress> m_dDNSinfo = new Dictionary<NetworkInterface, IPAddress>();
private ManagementEventWatcher m_watcher = null;
private NetworkAdapterInfo()
{
getDNSAddresses();
displayDNSInfo();
}
private static NetworkAdapterInfo _instance;
/*
* Instance creator (geter)
* */
public static NetworkAdapterInfo Instance
{
get
{
if (_instance == null)
{
_instance = new NetworkAdapterInfo();
}
return _instance;
}
}
/*
* Gets all DNS addresses for all Network cards
* Optionally changes all DNS addresses to a specified one
* */
private void getDNSAddresses()
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
if (dnsServers.Count > 0)
{
foreach (IPAddress dns in dnsServers)
{
if (IsIPv4(dns.ToString()))
{
m_dDNSinfo.Add(adapter, dns);
}
}
}
}
}
/*
* Displays the Network adapter DNS servers
* */
public void displayDNSInfo()
{
foreach (KeyValuePair<NetworkInterface, IPAddress> pair in m_dDNSinfo)
{
Console.WriteLine("Adapter: {0}\n DNS Server : {1}", pair.Key.Description, pair.Value.ToString());
}
}
/*
* Check to see if the ip is a valid one
* param value[in]: ip string
* @return true if it's a valid ip address
* */
public bool IsIPv4(string value)
{
var quads = value.Split('.');
// if we do not have 4 quads, return false
if (!(quads.Length == 4)) return false;
// for each quad
foreach (var quad in quads)
{
int q;
// if parse fails
// or length of parsed int != length of quad string (i.e.; '1' vs '001')
// or parsed int < 0
// or parsed int > 255
// return false
if (!Int32.TryParse(quad, out q)
|| !q.ToString().Length.Equals(quad.Length)
|| q < 0
|| q > 255) { return false; }
}
return true;
}
/*
* Used to verify if new DNS addresses found besides the ones already stored
* Optionally changes the DNS addreses
* */
private void checkIFDNSChanged()
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
if (dnsServers.Count > 0)
{
foreach (IPAddress dns in dnsServers)
{
if (IsIPv4(dns.ToString()))
{
bool dnsFound = false;
foreach (KeyValuePair<NetworkInterface, IPAddress> pair in m_dDNSinfo)
{
if (pair.Value.ToString() == dns.ToString())
{
dnsFound = true;
break;
}
}
if (dnsFound == false)
{
//DNS address changed
m_dDNSinfo.Add(adapter, dns);;
Console.WriteLine("Adapter: {0}\n new DNS Server : {1}",
adapter.Description, dns.ToString());
}
}
}
}
}
}
public void RegisterToDNSChanges()
{
try
{
string path = null;
int count = 0;
path += "(";
foreach (KeyValuePair<NetworkInterface, IPAddress> pair in m_dDNSinfo)
{
if (0 == count++)
{
path += "(KeyPath = 'SYSTEM\\\\CurrentControlSet\\\\services\\\\Tcpip\\\\Parameters\\\\Interfaces\\\\" + pair.Key.Id + "'" + " AND ValueName='NameServer')";
continue;
}
path += " OR (KeyPath = 'SYSTEM\\\\CurrentControlSet\\\\services\\\\Tcpip\\\\Parameters\\\\Interfaces\\\\" + pair.Key.Id + "'" + " AND ValueName='NameServer')";
}
path += ")";
//@"AND KeyPath = 'SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces\\{3E6EC2F0-C690-4CDA-BA57-5710EF53BEEC}' AND ValueName='NameServer'");
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM RegistryValueChangeEvent WHERE " +
"Hive = 'HKEY_LOCAL_MACHINE'" +
" AND " +
@path);
m_watcher = new ManagementEventWatcher(query);
//Console.WriteLine("Waiting for an event...");
// Set up the delegate that will handle the change event.
m_watcher.EventArrived += new EventArrivedEventHandler(HandleEvent);
// Start listening for events.
m_watcher.Start();
}
catch (ManagementException managementException)
{
Console.WriteLine("An error occurred: " + managementException.Message);
}
}
private void HandleEvent(object sender, EventArrivedEventArgs e)
{
//Console.WriteLine("Received an event.");
checkIFDNSChanged();
}
}
}
此代码正确提取网络适配器,并希望通过使用 ManagementEventWatcher 来查询每个网络适配器的 DNS 更改,并查询超过 1 个网络适配器 ID。对于 1 个单个网络适配器,它可以完美运行,但是当有 2 个时,我在该捕获机制中收到错误“发生错误:未找到”。
被拒绝的查询如下所示:
select * from RegistryValueChangeEvent where Hive = 'HKEY_LOCAL_MACHINE' AND ((KeyPath = 'SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces\\{3E6EC2F0-C690-4CDA-BA57-5710EF53BEEC}' AND ValueName='NameServer') OR (KeyPath = 'SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces\\{D92D94EF-A89E-4D73-B024-C0BD9E41FF75}' AND ValueName='NameServer'))
仅 1 个网络适配器的成功查询如下所示:
select * from RegistryValueChangeEvent where Hive = 'HKEY_LOCAL_MACHINE' AND ((KeyPath = 'SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces\\{3E6EC2F0-C690-4CDA-BA57-5710EF53BEEC}' AND ValueName='NameServer'))
您知道为什么 ManagementEventWatcher 会拒绝对 2 个不同网络适配器的查询吗?谢谢