#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.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)
{
printf("Error. Could not recover network reachability flags\n");
return 0;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
return ((isReachable && !needsConnection) || nonWiFi) ?
(([[NSURLConnection alloc] initWithRequest:[NSURLRequest
requestWithURL: [NSURL URLWithString:@"http://www.apple.com/"]
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0]
delegate:self]) ? YES : NO) : NO;
}