lostInTransit
lostInTransit

Reputation: 70997

iPhone - check if internet connectivity is available or not

I am using the following code to find out whether internet connectivity is present or not.

struct sockaddr_in zeroAddress; 
bzero(&zeroAddress, sizeof(zeroAddress)); 
zeroAddress.sin_len = sizeof(zeroAddress); 
zeroAddress.sin_family = AF_INET;

// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress); 
SCNetworkReachabilityFlags flags; 
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); 
CFRelease(defaultRouteReachability); 
if (!didRetrieveFlags) { 
    NSLog(@"Error. Could not recover network reachability flags"); 
    return 0; 
} 
BOOL isReachable = flags & kSCNetworkFlagsReachable; 
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; 
return (isReachable && !needsConnection) ? YES : NO; 

This method returns the expected result when my device is connected to a wifi network. But if I test the same method on a 3G or an Edge network, it returns a NO (i.e. not connected to the internet)

Any ideas why?

Thanks.

Upvotes: 0

Views: 902

Answers (2)

Look through Apple's code sample called "Reachability", and look at the top of the comments for how to use it in asynchronous mode:

http://developer.apple.com/IPhone/library/samplecode/Reachability/index.html

Upvotes: 6

Louis Gerbarg
Louis Gerbarg

Reputation: 43452

The issue is you are not actively connected, the cellular modem is powered down (which it does after a few seconds of inactivity). Chances are if you look you you will see that needsConnection is YES. Any of the higher level APIs (CFNetwork, NSURLConnection) will cause the connection to be established automatically.

You can test to see if you have cellular available by checking for the kSCNetworkReachabilityFlagsIsWWAN key.

Upvotes: 0

Related Questions