特定ip /端口的可达性测试

时间:2013-07-03 08:22:07

标签: ios objective-c sockets reachability

我正在尝试检查地址和端口是否可用。为此,我按照这篇文章中的不同步骤(iphone) reachability test for specific ip/port?和我的代码:

BOOL hasLeadingNumberInString(NSString* s) {
    if (s)
        return [s length] && isnumber([s characterAtIndex:0]);
    else
        return NO;
}

-(BOOL)networkConnected: (NSString *)ipAdress Port:(int)port {
    SCNetworkReachabilityFlags  flags = 0;
    SCNetworkReachabilityRef    netReachability;
    BOOL                        retrievedFlags = NO;

    // added the "if" and first part of if statement
    //
    if (hasLeadingNumberInString(ipAdress)) {
        struct sockaddr_in the_addr;
        memset((void *)&the_addr, 0, sizeof(the_addr));
        the_addr.sin_family = AF_INET;
        the_addr.sin_port = htons(port);
        const char* server_addr = [ipAdress UTF8String];
        unsigned long ip_addr = inet_addr(server_addr);
        the_addr.sin_addr.s_addr = ip_addr;
        netReachability =    SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (struct sockaddr*)&the_addr);
    } else {
        netReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [ipAdress UTF8String]);
    }
    if (netReachability) {
        retrievedFlags = SCNetworkReachabilityGetFlags(netReachability, &flags);
        CFRelease(netReachability);
    }
    if (!retrievedFlags || !flags) {
        return NO;
    }
    return YES;
}

但即使存在一对地址/端口,我也总是没有。我做错了什么?

编辑日志:

netReachability is NIL

2 个答案:

答案 0 :(得分:3)

the_addr.sin_len = sizeof(the_addr);

您忘了设置结构的这一部分。没有它,它将被解释为零长度(无效)。如果您进行了设置,则SCNetworkReachabilityRef将不再是NULL

答案 1 :(得分:2)

SCNetworkReachabilityCreateWithAddress()失败,因为您忘了设置

the_addr.sin_len = sizeof(the_addr);

如果你补充说它应该有用。

但请注意,SCNetworkReachability函数仅检查数据包是否可以路由 到目的地。如果主机实际正在侦听给定端口,它不验证

因此,端口号无关紧要,您只需使用

即可
netReachability  = SCNetworkReachabilityCreateWithName(NULL, server_addr);

没有struct sockaddr_in麻烦。