通过linq在iPhone上的Monotouch/Xamarin上获取IP地址 [英] Get IP Address on Monotouch/Xamarin in iphone via linq
问题描述
我是linq的新手,并且想用它来获取iOS设备的ip地址.我想知道是否有人对此方法有任何疑问(基于
I'm new to linq, and want to use it to get the ip address of an iOS device. I was wondering if anyone sees any problems with this approach (based on this How do I get the network interface and its right IPv4 address? ) or if there is a better/more compact/more clean way to do it.
// get my IP
string ip = NetworkInterface.GetAllNetworkInterfaces()
.Where(x => x.Name.Equals("en0"))
.Select(n => n.GetIPProperties().UnicastAddresses)
.Where(x => x.First().Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
.Select(x => x.First().Address.ToString());
推荐答案
我认为您代码的问题在于最后一个Select
.
Where
选择器已经返回了IEnumerable
,这意味着此时您的IEnumerable
为UnicastIPAddressInformationCollection
.然后在那一点上,只需选择第一个并指向address属性,然后使用以下命令将其转换为字符串:.First().Address.ToString()
I think the problem with your code lies with the last Select
.
The Where
selector already returns an IEnumerable
, which means at that point you have an IEnumerable
of UnicastIPAddressInformationCollection
. Then at that point, just select the first one and point to the address property and convert to string using: .First().Address.ToString()
以下是为我完成工作的示例:
Here's an example that did the job for me:
public string IpEndPoint
{
get
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(ni => ni.Name.Equals("en0"))
.First().GetIPProperties().UnicastAddresses
.Where(add => add.Address.AddressFamily == AddressFamily.InterNetwork)
.First().Address.ToString();
}
}
这篇关于通过linq在iPhone上的Monotouch/Xamarin上获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!