使用MonoTouch中的Bonjour NSNetService从NSData获取IP地址?

时间:2014-02-13 01:51:54

标签: c# ios xamarin.ios bonjour nsnetservice

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

传递给resolve事件处理程序的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地址的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

NSNetService.Addresses属性为您提供NSData个实例,这些实例必须转换为IPAddress(或其他.NET类型)可以消化的内容。 E.g。

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