0

我正在尝试检查地址和端口是否可用。为此,我按照这篇文章(iphone)中针对特定 ip/端口的可达性测试中的不同步骤进行操作?和我的代码:

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
4

2 回答 2

3

the_addr.sin_len = sizeof(the_addr);

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

于 2013-07-03T09:37:09.480 回答
2

失败是SCNetworkReachabilityCreateWithAddress()因为你忘了设置

the_addr.sin_len = sizeof(the_addr);

如果您添加它应该可以工作。

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

因此,端口号无关紧要,您可以使用

netReachability  = SCNetworkReachabilityCreateWithName(NULL, server_addr);

没有所有的struct sockaddr_in麻烦。

于 2013-07-03T09:49:35.177 回答