iOS。通过 IP 获取同一本地网络中的其他设备/计算机名称

Nik*_*kov 6 networking cocoa lan ios

我的程序的一项任务是扫描本地 Wi-Fi 网络以查找同一网络中的任何设备/计算机。我找到了获取所有工作设备 IP 的解决方案,但未能获取它们的名称。我没有找到任何解决这个问题的线索。有什么建议么?

nei*_*lco 5

为了执行反向 DNS 查找,您需要调用该CFHostGetNames函数,如下所示:

+ (NSArray *)hostnamesForIPv4Address:(NSString *)address
{
    struct addrinfo *result = NULL;
    struct addrinfo hints;

    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 succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
    if (!succeeded) {
        return nil;
    }

    NSMutableArray *hostnames = [NSMutableArray array];

    CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
    for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
        [hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
    }

    return hostnames;
}
Run Code Online (Sandbox Code Playgroud)