您可以使用 IPInterfaceProperties.DnsAddresses 获取 DNS 服务器的 IP。可以在此处找到代码示例:http: //msdn.microsoft.com/en-us/library/system.net.networkinformation.ipinterfaceproperties.dnsaddresses.aspx
然后,您可以使用此处找到的组件查询该服务器:http: //www.codeproject.com/Articles/12072/C-NET-DNS-query-component
您可以通过查询 SOA 记录找到主 DNS 服务器。
List<IPAddress> dnsServers = new List<IPAddress>();
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
IPAddressCollection adapterDnsServers = adapterProperties.DnsAddresses;
if (adapterDnsServers.Count > 0)
dnsServers.AddRange(adapterDnsServers);
}
foreach (IPAddress dnsServer in (from d in dnsServers
where d.AddressFamily == AddressFamily.InterNetwork
select d))
{
Console.WriteLine("Using server {0}", dnsServer);
// create a request
Request request = new Request();
// add the question
request.AddQuestion(new Question("stackoverflow.com", DnsType.MX, DnsClass.IN));
// send the query and collect the response
Response response = Resolver.Lookup(request, dnsServer);
// iterate through all the answers and display the output
foreach (Answer answer in response.Answers)
{
MXRecord record = (MXRecord)answer.Record;
Console.WriteLine("{0} ({1}), preference {2}", record.DomainName, Dns.GetHostAddresses(record.DomainName)[0], record.Preference);
}
Console.WriteLine();
}
Console.ReadLine();