【问题标题】:iOS. get other device/computer name by IP in the same local networkIOS。通过IP在同一本地网络中获取其他设备/计算机名称
【发布时间】:2013-10-15 08:06:18
【问题描述】:

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

【问题讨论】:

  • 您是如何获得所有工作设备的列表的?用于扫描的代码是什么。我尝试了很多来自互联网的代码,但无法实现这个@Nikolay Shubenkov
  • 检测您的 IP。我的 IP 是,例如 192.168.2.44,然后 ping 所有地址从 192.168.2.1 到 192.168.2.255 的 IP。如果您需要代码,请在 StackOverflow 上创建问题,发布该问题的链接,我会将项目发布到 github 并放置指向该项目的链接以回答您的问题。
  • 这是该问题的link。 @Nikolay Shubenkov
  • @NikolayShubenkov 您从 IP 地址获取计算机名称成功了吗?
  • 很遗憾没有。至少现在。这是一个很老的问题,我不能重新检查这个,因为项目代码只是不编译。

标签: ios cocoa networking lan


【解决方案1】:

为了执行反向 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;
}

【讨论】:

  • 我试过你的代码,但我总是从那个函数中得到空值。我正在尝试在 iOS 应用程序中获取计算机名称。请您建议我找到计算机名称的正确方法。谢谢
  • 上述函数此时无法获取某些网络的主机名并返回 null 。 BOOL 成功 = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL); if (!succeeded) { 返回零; } 。知道为什么
【解决方案2】:

BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);现在遇到总是在这一行失败,我尝试使用getnameinfo函数,仍然无法获取主机名

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 2011-06-14
    • 2012-11-04
    • 2012-08-19
    • 2022-06-17
    相关资源
    最近更新 更多