4

当我得到一个 NetService 对象时,我尝试这样做:</p>

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

关于委托方法:</p>

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

谢谢。

4

2 回答 2

6
// 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

于 2013-08-25T10:39:51.597 回答
0

我发现了一篇建议以下解决方案的帖子。

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

虽然它确实我输出人类可读的字符串......它可能对你有用。


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

<10026a5e 0a0a7893 00000000 00000000>

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

10.10.120.147 // 0a0a7893

我编写了一个进行转换的主机类NSString可以在此处找到扩展名。我只使用前 16 字节地址,而忽略所有其他地址。随意扩展课程。

于 2012-09-25T09:28:38.153 回答