问题
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());
回答1:
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();
}
}
回答2:
Selecting .First().Address
only once:
string ip = NetworkInterface
.GetAllNetworkInterfaces()
.Where(x => x.Name.Equals("en0"))
.Select(n => n.GetIPProperties().UnicastAddresses.First().Address)
.Where(x => x.AddressFamily == AddressFamily.InterNetwork);
来源:https://stackoverflow.com/questions/17843925/get-ip-address-on-monotouch-xamarin-in-iphone-via-linq