c# - 通过 linq 在 iphone 中的 Monotouch/Xamarin 上获取 IP 地址

标签 c# ios linq ip-address

我是 linq 的新手,想用它来获取 iOS 设备的 IP 地址。我想知道是否有人发现这种方法有任何问题(基于此 How do I get the network interface and its right IPv4 address? ),或者是否有更好/更紧凑/更干净的方法来做到这一点。

  // 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());

最佳答案

我认为您的代码的问题在于最后的SelectWhere 选择器已经返回一个 IEnumerable,这意味着此时您有一个 UnicastIPAddressInformationCollectionIEnumerable。然后在这一点上,只需选择第一个并指向地址属性并使用以下方法转换为字符串:.First().Address.ToString()

这是一个为我完成工作的例子:

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();
        }
    }

关于c# - 通过 linq 在 iphone 中的 Monotouch/Xamarin 上获取 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17843925/

相关文章:

ios - MKMapView 内的自定义核心图形叠加 : can't display stroked ellipse

ios - afnetworking 3.0 迁移 : how to POST with headers and HTTP Body

c# - 从另一个列表 LINQ 获取仅包含第一个和最后一个字符的字符串列表

c# - 如何测试 API

c# - 在 Windows 上使用 Xamarin 进行 iOS UI 测试

ios - 类型 'AuthDataResult' 的值没有成员 'isEmailVerification'

c# - 使用 LINQ 计算特定列的总和

c# - 在 DBML 中使用 LINQ 的多个连接表中的多个搜索参数

c# - 访问静态数据的设计模式

c# - "There was an error trying to log you in: ' ' "Blazor WebAssembly 使用 IdentiyServer 身份验证