作为任务的一部分,我必须扫描我的局域网并获取连接到wifi的设备的名称。我浏览了苹果文档this以及许多其他S.O链接,例如this。但是,没有发生解决方案,会发生一些错误。我不是一个网络人,所以大多数人对我来说都是希腊人。一个几乎相同的问题被问到here 这是我的代码。我写下了评论中发生的错误。
另一个答案也会有所帮助。
+ (NSArray *)hostnamesForAddress:(NSString *)address {
// Get the host reference for the given address.
CFStreamError streamError;
struct addrinfo hints;
struct addrinfo *result = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], NULL, &hints, &result);
if (errorStatus != 0) return nil;
CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result->ai_addr, result->ai_addrlen);
if (addressRef == nil) return nil;
freeaddrinfo(result);
CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
if (hostRef == nil) return nil;
CFRelease(addressRef);
BOOL isSuccess = CFHostStartInfoResolution(hostRef, kCFHostNames, &streamError);
// always false
if (!isSuccess){
NSLog(@"error:%@",[self convertCFStreamErrorIntoNSError:streamError]);
// error:Error Domain=kCFErrorDomainCFNetwork Code=2 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.)" UserInfo=0x1cd29190 {kCFGetAddrInfoFailureKey=8}
return nil;
}
// Get the hostnames for the host reference.
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
NSMutableArray *hostnames = [NSMutableArray array];
for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}
return hostnames[0];
}