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

后端 未结 2 759
天涯浪人
天涯浪人 2021-01-21 00:31

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 name

相关标签:
2条回答
  • 2021-01-21 00:52

    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;
    }
    
    0 讨论(0)
  • 2021-01-21 00:52

    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

    0 讨论(0)
提交回复
热议问题