我想知道如何在monotouch中获得默认的DNS服务器?
这段代码在模拟器中运行得很好,但在设备上给出了0条记录。
NetworkInterface.GetAllNetworkInterfaces();
foreach (IPAddress ipAddr in ipProps.DnsAddresses)
Console.WriteLine(ipAddr);
另一方面,该代码在模拟器和设备上都有效:
IPHostEntry he = Dns.GetHostEntry(domain);
dns = he.HostName.ToString();
有了这些,我假设DNS服务器地址存储在某个地方。我的意思是它是可访问的。如何获取其IP?
这将获得MonoTouch中的IP地址:-
public string GetIPAddress()
{
string address = "Not Connected";
try
{
#if SIM
address = IPAddress.FileStyleUriParser("127.0.0.1");
#else
string str = Dns.GetHostName() + ".local";
IPHostEntry hostEntry = Dns.GetHostEntry(str);
address = (
from addr in hostEntry.AddressList
where addr.AddressFamily == AddressFamily.InterNetwork
select addr.ToString()
).FirstOrDefault();
#endif
}
catch (Exception ex)
{
// Add error handling....
}
return address;
}
注意使用模拟器和设备之间的区别。
我不相信这样的API在iOS上存在(但我很乐意被证明是错误的)。其他需要这些信息的项目依赖于一些技巧,比如使用众所周知的静态地址到DNS服务器)来克服这一问题。
现在原因代码如下:
var all = NetworkInterface.GetAllNetworkInterfaces ();
foreach (NetworkInterface ni in all) {
var props = ni.GetIPProperties ();
foreach (var dns in props.DnsAddresses) {
Console.WriteLine (dns);
}
}
在模拟器上运行是因为它是一个模拟器,而不是模拟器。IOW主机(Mac)计算机所允许的东西远远超过真实iOS设备所允许的。
更确切地说,props
将是System.Net.NetworkInformation.MacOsIPInterfaceProperties
的一个实例,它继承自UnixIPInterfaceProperties
,并最终读取/etc/resolv.conf
文件(iOS禁止您的应用程序读取该文件)。
第二种情况,调用Dns.GetHostEntry
,进入Mono运行时,但最终调用gethostname
,这不需要调用者知道DNS服务器地址。