Skip to content

Instantly share code, notes, and snippets.

@eiffelqiu
Created May 25, 2011 00:44
Show Gist options
  • Save eiffelqiu/990085 to your computer and use it in GitHub Desktop.
Save eiffelqiu/990085 to your computer and use it in GitHub Desktop.
Checking network availability on iOS
#include <netinet/in.h>
#import <SystemConfiguration/SCNetworkReachability.h>
- (BOOL)connectedToNetwork {
// Create zero addy
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;
}
// How to use
if ([self connectedToNetwork]) {
//yes we're connected
}
else {
//no we're not connected
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment