我正在尝试检查地址和端口是否可用。为此,我按照这篇文章(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