iOS. get other device/computer name by IP in the same local network

こ雲淡風輕ζ 提交于 2019-12-31 03:05:16

问题


One task of my program is to scan local wi-fi network for any devices/computers in same network. I found solution to get all working devices IPs, but did not managed to get names of them. I did not find any clue to solve this problem. Any suggestions?


回答1:


In order to perform a reverse DNS lookup, you need to call the CFHostGetNames function, like this:

+ (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;
}



回答2:


BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL); Now I encounter that always failed at this line, and I tried to use getnameinfo function, it is still can't get the hostname



来源:https://stackoverflow.com/questions/19376123/ios-get-other-device-computer-name-by-ip-in-the-same-local-network

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!