I am trying to check the reachability of a device on WIFI
I have modified code from Maher Ali's book "Advanced IOS4 Programming" to use an IP address as follows
- (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;
}
But it always returns NO using an IP address and port that I know I can connect to (ie if I skip this check, all goes well)
I am trying to connect to "10.0.0.59" port 1001 which I can do
it does compile - and I have stepped (on an ipod) through and it is running through the socket section of the code.
netReachability is returned as zero.
relevant headers included are
#import "Reachability.h"
#include <CFNetwork/CFSocketStream.h>
#include <arpa/inet.h>
Can anybody spot what I am doing wrong?
I use Tony Million's newer Reachability that makes stuff like this very easy. To do this you could just do something like:
if([[Reachability reachabilityForLocalWiFi] isReachable]) {
// It's reachable on wifi
}
Not sure if this help but I use Reachability.h from apple everytime I want to check if the app is connected to internet(or any internal IP)
here is my code
#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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.