Get IP Address on Monotouch/Xamarin in iphone via linq

限于喜欢 提交于 2019-12-25 18:40:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!