我正在尝试检查设备在WIFI上的可访问性
我修改了Maher Ali的书“Advanced IOS4 Programming”中的代码,使用如下的IP地址
- (BOOL) networkConnected: (NSString *) addr {
SCNetworkReachabilityFlags flags = 0;
SCNetworkReachabilityRef netReachability;
BOOL retrievedFlags = NO;
// added the "if" and first part of if statement
//
if (hasLeadingNumberInString(addr)) {
struct sockaddr_in the_addr;
memset((void *)&the_addr, 0, sizeof(the_addr));
the_addr.sin_family = AF_INET;
the_addr.sin_port = htons(1001);
const char* server_addr = [addr 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, [addr UTF8String]);
}
if (netReachability) {
retrievedFlags = SCNetworkReachabilityGetFlags(netReachability, &flags);
CFRelease(netReachability);
}
if (!retrievedFlags || !flags) {
return NO;
}
return YES;
}
但它始终使用我知道可以连接的IP地址和端口返回NO (即如果我跳过这个检查,一切顺利)
我正在尝试连接到“10.0.0.59”端口1001,我可以这样做
它确实编译 - 我已经步入(在ipod上)并且它正在运行代码的套接字部分。
netReachability返回为零。
包含的相关标题是
#import "Reachability.h"
#include <CFNetwork/CFSocketStream.h>
#include <arpa/inet.h>
有人能发现我做错了吗?
答案 0 :(得分:1)
我使用Tony Million的newer Reachability这样的东西非常简单。要做到这一点,你可以做类似的事情:
if([[Reachability reachabilityForLocalWiFi] isReachable]) {
// It's reachable on wifi
}
答案 1 :(得分:0)
不确定是否有这个帮助,但每次我想检查应用是否连接到互联网(或任何内部IP)时,我都会使用来自苹果的Reachability.h
这是我的代码
#import "Reachability.h"
if([[Reachability sharedReachability] internetConnectionStatus] == NotReachable) {
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"You require an internet connection via WiFi or cellular network for location finding to work." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[myAlert show];
[myAlert release];
}else{
// Do something
}