gpt4 book ai didi

iphone - 如何从 NetService 获取 IP 地址

转载 作者:行者123 更新时间:2023-12-03 19:41:31 27 4
gpt4 key购买 nike

当我得到一个NetService对象时,我尝试做:

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

关于委托(delegate)方法:

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

关于iphone - 如何从 NetService 获取 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12558305/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com