0

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());
Community
  • 1
  • 1
reza
  • 1,329
  • 2
  • 22
  • 37

2 Answers2

2

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();
        }
    }
Jay M
  • 979
  • 1
  • 12
  • 23
  • Although this code may help to solve the problem, it doesn't explain _why_ and/or _how_ it answers the question. Providing this additional context would significantly improve its long-term educational value. Please [edit] your answer to add explanation, including what limitations and assumptions apply. – Toby Speight Aug 30 '16 at 16:57
  • 1
    This seems to fail while using on mobile data.But, works fine on WiFi. – Shailesh Mar 04 '21 at 09:01
1

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);
It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
  • I ended up using this.. var ip = NetworkInterface.GetAllNetworkInterfaces().Where(x => x.Name.Equals("en0")).First().GetIPProperties().UnicastAddresses.Where(x=>x.Address.AddressFamily == AddressFamily.InterNetwork).First().Address.ToString(); – reza Jul 27 '13 at 01:05