因此,我正在使用Xamarin和.net在iOS项目中实现uPNP。我一直在努力获取本地设备(即正在运行程序的设备)的有效本地IP地址。
我尝试使用NetworkInterface.GetAllNetworkInterfaces()
,但是Xamarin在该方法的实现中存在一个错误,因此不起作用。
因此,我环顾四周,发现了一种简单的方法来完成此任务。我尝试了以下方法:
IPAddress[] hostAddresses = Dns.GetHostAddresses(Dns.GetHostName());
上面引发了“无法解析主机...”异常(其中...是我的设备名称)。
因此它确实获得了我的设备名称,但随后无法解析它。
这段代码在WPF应用程序的Windows下工作正常。
在iPhone或iPad模拟器上的MAC上使用Xamarin Studio可以很好地工作。
但是,当我尝试让MAC在我的实际iPad设备上启动该应用程序时,出现以下异常:
System.Net.Sockets.SocketException:无法解析主机“Charrison”
在System.Net.Dns.Error_11001(System.String hostName)[0x00000]中
/开发人员/ MonoTouch /源/mono/mcs/class/System/System.Net/Dns.cs:298
在System.Net.Dns.hostent_to_IPHostEntry(System.String
originalHostName,System.String h_name,System.String [] h_aliases,
System.String [] h_addrlist)[0x00082]在
/开发人员/ MonoTouch /源/mono/mcs/class/System/System.Net/Dns.cs:326
在System.Net.Dns.GetHostByName(System.String hostName)[0x0002a]中
/开发人员/ MonoTouch /源/mono/mcs/class/System/System.Net/Dns.cs:467
在System.Net.Dns.GetHostEntry(System.String hostNameOrAddress)
[0x00061]在
/开发人员/ MonoTouch /源/mono/mcs/class/System/System.Net/Dns.cs:406
在System.Net.Dns.GetHostAddresses(System.String hostNameOrAddress)
[0x00065]在
/开发人员/ MonoTouch /源/mono/mcs/class/System/System.Net/Dns.cs:432
在UpnpUI_iOS.DeviceViewController.startButton_TouchUpInside
(System.Object发送方,System.EventArgs e)[0x0008c]在
/Users/engineering/Projects/UpnpUI_iOS/DeviceViewController.cs:83位于
MonoTouch.UIKit.UIControlEventProxy.Activated()[0x00000]在
/Developer/MonoTouch/Source/monotouch/src/UIKit/UIControl.cs:30,位于
在(包装器管理到本地)
MonoTouch.UIKit.UIApplication:UIApplicationMain
(int,string [],intptr,intptr)在MonoTouch.UIKit.UIApplication.Main
(System.String [] args,System.StringPrincipalClassName,System.String
proxyClassName)[0x0004c]在
/Developer/MonoTouch/Source/monotouch/src/UIKit/UIApplication.cs:38
在UpnpUI_iOS.Application.Main(System.String [] args)[0x00008]中
/Users/engineering/Projects/UpnpUI_iOS/Main.cs:17
如果有人知道某种不错的,快速的方法来获取本地设备的有效IP地址,该地址将在使用Xamarin的.net在iPad上实际运行,请告诉我。我真的很感激。
预先感谢您的有用建议。
最佳答案
从Mike Bluestein在forums中被盗
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces()) {
if (netInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 ||
netInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet) {
foreach (var addrInfo in netInterface.GetIPProperties().UnicastAddresses) {
if (addrInfo.Address.AddressFamily == AddressFamily.InterNetwork) {
var ipAddress = addrInfo.Address;
// use ipAddress as needed ...
}
}
}
}
关于ios - 调用Dns.GetHostAddresses(Dns.GetHostName())时无法解决主机异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17885130/