简体   繁体   中英

Reachability returning inaccurate status

I have a simple Reachability code that returns if I can connect to a server or not:

-(BOOL)checkConnectionForHost:(NSString*)host{
   _checkStatus = [Reachability reachabilityWithHostname:host];
   NetworkStatus networkStatus = [_checkStatus currentReachabilityStatus];
   return networkStatus != NotReachable;
}

I tested it by adding stuff like google.com , and it works fine. However, if I type in a junk number like 8170319837018 , and call this function, it still return TRUE . However, if I add any char to it, like 8170319837018a , it will return FALSE , as it should. Am I calling the wrong method on Reachability ? Do I have to check if the string is a URL or an IP address?

Thanks!

Reachability has some issues. If You are connected to wifi it will return it's rechable but doesn't actually ping the host. Better way would be to use NSURLCONNECTION to ping the server directly

+ (BOOL)pingURL:(NSString *)url
{
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1];
    NSURLResponse *response = nil;
    NSError *error = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"response %d", [(NSHTTPURLResponse *)response statusCode]);
    if ([(NSHTTPURLResponse *)response statusCode] == 200) {
        return YES;
    }

    return NO;
}

I think this is because the internal reachability flags are long numbers. So when you pass 8170319837018 the [_checkStatus currentReachabilityStatus] must be returning some number which is not equal to NotReachable(0) and that's why it must be returning TRUE. What you can instead do is to check against each type of reachability like below:

-(BOOL)checkConnectionForHost:(NSString*)host{
   _checkStatus = [Reachability reachabilityWithHostname:host];
   NetworkStatus networkStatus = [_checkStatus currentReachabilityStatus];
   return (networkStatus == ReachableViaWiFi) || (networkStatus == ReachableViaWWAN);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM