Friday, June 21, 2013

NSNetService addresses example in Objective C (iOS).


NSNetService addresses

Returns an array containing NSData objects, each of which contains a socket address for the service.

- (NSArray *)addresses

Return Value
An array containing NSData objects, each of which contains a socket address for the service. Each NSData object in the returned array contains an appropriate sockaddr structure that you can use to connect to the socket. The exact type of this structure depends on the service to which you are connecting. If no addresses were resolved for the service, the returned array contains zero elements.

Discussion of [NSNetService addresses]
It is possible for a single service to resolve to more than one address or not resolve to any addresses. A service might resolve to multiple addresses if the computer publishing the service is currently multihoming.

NSNetService addresses example.
for (NSData* data in [server addresses]) {

    char addressBuffer[100];

    struct sockaddr_in* socketAddress = (struct sockaddr_in*) [data bytes];

    int sockFamily = socketAddress->sin_family;

    if (sockFamily == AF_INET || sockFamily == AF_INET6) {

        const char* addressStr = inet_ntop(sockFamily,
                            &(socketAddress->sin_addr), addressBuffer,
                            sizeof(addressBuffer));

        int port = ntohs(socketAddress->sin_port);

        if (addressStr && port)
            NSLog(@"Found service at %s:%d", addressStr, port);

    }

}

Example of [NSNetService addresses].
for (NSData *address in [service addresses]) {
struct sockaddr_in *socketAddress = (struct sockaddr_in *) [address bytes];
            NSLog(@\"Service name: %@ , ip: %s , port %i\", [service name], inet_ntoa(socketAddress->sin_addr), [service port]);
        }

NSNetService addresses example.
@implementation NSNetService (ipv4)

- (NSArray*)ipv4addresses
{
        NSMutableArray * ipv4addresses = [NSMutableArray array];
        NSArray *addresses = [self addresses];
        int aCount = [addresses count];
        char addr[256];
       
        for (int i = 0; i < aCount; i++) {
                struct sockaddr *socketAddress = (struct sockaddr *)[[addresses 
objectAtIndex:i] bytes];
               
                if (socketAddress && socketAddress->sa_family == AF_INET) {
                        if (inet_ntop(AF_INET, &((struct sockaddr_in *)socketAddress)-
 >sin_addr, addr, sizeof(addr))) {
                               
                                uint16_t port = ntohs(((struct sockaddr_in *)socketAddress)-
 >sin_port);
                               
                                [ipv4addresses addObject:[NSString stringWithFormat:@"%s:%d", 
addr, port]];
                        }
                }
        }
       
        return ipv4addresses;
}

@end


End of NSNetService addresses example article.