本文介绍了如何从NetService获取IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I get a NetService object,I try to do:

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?
   */
}

谢谢。

推荐答案

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

This is the outputClient Address: IP4: 192.168.69.38 Port: 58612

这篇关于如何从NetService获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 17:35