3

我在 iOS 上使用 Xamarin + MonoTouch 来浏览网络上的 Web 服务器,然后我可以从中下载文件。

传递给解析事件处理程序的 NSNetService 包含地址作为 NSData。我找不到将 NSData 转换为实际 IP 地址的好方法,然后我可以从中构建 URL,即 http:// < IPAddress > /folder/file.htm

这是我的 NSNetService.AddressResolved 事件处理程序:

private void OnServiceResolved(object sender, EventArgs args)
{
        NSNetService service = (NSNetService)sender;
        // service.Port is valid.
        // service.HostName is valid.
        // but we want the IP addres, which is in service.Addresses.
        // None of the following four methods works quite right.
        IPAddress address = (IPAddress)service.Addresses [0]; // Cannot convert type NSData to IPAddress
        SocketAddress address2 = (SocketAddress)service.Addresses[0]; // Cannot convert NSData to SocketAddress. A binary copy might work?
        IPHostEntry entry = (IPHostEntry)service.Addresses [0]; // Cannot convert NSData to IPHostEntry
        IPHostEntry entry2 = Dns.GetHostByName (service.HostName); // This kinda works, but is dumb. Didn't we just resolve?
}

在解析事件中从 NSNetService 获取服务 IP 地址的正确方法是什么?

4

1 回答 1

4

NSNetService.Addresses属性为您提供了NSData必须转换为IPAddress(或其他 .NET 类型)可以消化的东西的实例。例如

MemoryStream ms = new MemoryStream ();
(ns.Addresses [0] as NSData).AsStream ().CopyTo (ms);
IPAddress ip = new IPAddress (ms.ToArray ());

请注意,这可能会返回一个 IPv6 地址(或IPAddress不接受的格式)。您可能想要迭代所有内容Addresses以找到最好的。

我将考虑在 Xamarin.iOS 的未来版本中添加一种便捷方法。

更新

一个更完整的版本,返回一个IPAddress,看起来像:

static IPAddress CreateFrom (NSData data)
{
    byte[] address = null;
    using (MemoryStream ms = new MemoryStream ()) {
        data.AsStream ().CopyTo (ms);
        address = ms.ToArray ();
    }
    SocketAddress sa = new SocketAddress (AddressFamily.InterNetwork, address.Length);
    // do not overwrite the AddressFamily we provided
    for (int i = 2; i < address.Length; i++)
        sa [i] = address [i];
    IPEndPoint ep = new IPEndPoint (IPAddress.Any, 0);
    return (ep.Create (sa) as IPEndPoint).Address;
}
于 2014-02-22T17:45:05.033 回答