iPhone: Bonjour NSNetService IP address and port

前端 未结 3 1482
礼貌的吻别
礼貌的吻别 2021-01-31 05:47

Excuse my iPhone/Objective-C newbie status please!

I\'ve found my HTTP server using NSNetServiceBrowser, but now I just want the IP address and port of the service found

3条回答
  •  轮回少年
    2021-01-31 06:05

    I realize this is an old thread, but I've just run across this as well. There are a few problems with the code above:

    1. It's not IPv6 savvy. At a minimum, it should detect and discard IPv6 addresses if the rest of your app can only handle v4 addresses, but ideally you should be prepared to pass both address families upstream.

    2. The port assignment will generate incorrect values for Intel processors. You need to use htons to fix that.

    3. As Andrew noted above, the iteration should use the enhanced for loop.

    4. (EDIT: Added this) As noted on another related thread, the use of inet_ntoa is discouraged in favor of inet_ntop.

    Putting all of this together, you get:

    char addressBuffer[INET6_ADDRSTRLEN];
    
    for (NSData *data in self.addresses)
    {
        memset(addressBuffer, 0, INET6_ADDRSTRLEN);
    
        typedef union {
            struct sockaddr sa;
            struct sockaddr_in ipv4;
            struct sockaddr_in6 ipv6;
        } ip_socket_address;
    
        ip_socket_address *socketAddress = (ip_socket_address *)[data bytes];
    
        if (socketAddress && (socketAddress->sa.sa_family == AF_INET || socketAddress->sa.sa_family == AF_INET6))
        {
            const char *addressStr = inet_ntop(
                    socketAddress->sa.sa_family,
                    (socketAddress->sa.sa_family == AF_INET ? (void *)&(socketAddress->ipv4.sin_addr) : (void *)&(socketAddress->ipv6.sin6_addr)),
                    addressBuffer,
                    sizeof(addressBuffer));
    
            int port = ntohs(socketAddress->sa.sa_family == AF_INET ? socketAddress->ipv4.sin_port : socketAddress->ipv6.sin6_port);
    
            if (addressStr && port)
            {
                NSLog(@"Found service at %s:%d", addressStr, port);
            }
        }
    }
    

提交回复
热议问题