如何从NetService获取IP地址

时间:2012-09-24 02:54:51

标签: iphone xcode ip-address data-conversion nsnetservice

当我获得NetService对象时,我会尝试:

NSNetService *ss=[netArray objectAtIndex:indexPath.row];
ss.delegate=self;
[ss resolveWithTimeout:3.0];

关于委托方法:

-(void)netServiceDidResolveAddress:(NSNetService *)sender
{
   NSArray *address=sender.addresses;
   NSData *addressData=[NSData dataWithBytes:address length:sizeof(address)];
   /*
   How?
   */
}

感谢。

2 个答案:

答案 0 :(得分:4)

// Sent when addresses are resolved
- (void)netServiceDidResolveAddress:(NSNetService *)netService
{
    // Make sure [netService addresses] contains the
    // necessary connection information
    if ([self addressesComplete:[netService addresses]
                 forServiceType:[netService type]]) {
        [services addObject:netService];
    }
}

// Verifies [netService addresses]
- (BOOL)addressesComplete:(NSArray *)addresses
           forServiceType:(NSString *)serviceType
{

    // Perform appropriate logic to ensure that [netService addresses]
    // contains the appropriate information to connect to the service

    NSData *myData = nil;
    myData = [addresses objectAtIndex:0];

    NSString *addressString;
    int port=0;
    struct sockaddr *addressGeneric;
    struct sockaddr_in addressClient;


    addressGeneric = (struct sockaddr *) [myData bytes];

    switch( addressGeneric->sa_family ) {
        case AF_INET: {
            struct sockaddr_in *ip4;
            char dest[INET_ADDRSTRLEN];
            ip4 = (struct sockaddr_in *) [myData bytes];
            port = ntohs(ip4->sin_port);
            addressString = [NSString stringWithFormat: @"IP4: %s Port: %d", inet_ntop(AF_INET, &ip4->sin_addr, dest, sizeof dest),port];
        }
            break;

        case AF_INET6: {
            struct sockaddr_in6 *ip6;
            char dest[INET6_ADDRSTRLEN];
            ip6 = (struct sockaddr_in6 *) [myData bytes];
            port = ntohs(ip6->sin6_port);
            addressString = [NSString stringWithFormat: @"IP6: %s Port: %d",  inet_ntop(AF_INET6, &ip6->sin6_addr, dest, sizeof dest),port];
        }
            break;
        default:
            addressString=@"Unknown family";
            break;
    }

    NSLog(@"Client Address: %@",addressString);


    return YES;
}

这是输出 客户地址:IP4:192.168.69.38端口:58612

答案 1 :(得分:0)

我发现a post表明了以下解决方案。

NSString* addressString = [[NSString alloc] initWithData:addressData encoding:NSASCIIStringEncoding];

虽然它输出一个人类可读的字符串...它可能适合你。


这是打印NSData对象时写入控制台的内容。

<10026a5e 0a0a7893 00000000 00000000>

与此同时,我发现第二段是ip-address的十六进制形式。在这个例子中它是......

10.10.120.147 // 0a0a7893

我写了一个Host class进行转换。可以找到NSString扩展名here。我只使用第一个16字节地址而忽略所有其他地址。随意扩展课程。