6

I need to determine if Internet Connection is available or not. I don't care how it is connected (WI-FI, Lan,etc..) . I need to determine, is Internet Connection available at all .

P.S. I found a way to check WI-FI connection. But I don't care how it is connected (I need to check all the ways that can be connected to Internet).

Something like (isConnected)

User1234
  • 2,332
  • 3
  • 25
  • 53
  • 1
    Dupe of http://stackoverflow.com/questions/2995822/check-internet-connection-in-cocoa-application – bryanmac Oct 02 '11 at 15:12
  • It's nor realy duplicate. that link is more about Iphone Internet Connection. And for Wi-Fi only. – User1234 Oct 02 '11 at 15:27
  • @User1234: What leads you to believe that questioner was asking about the iPhone or Wi-Fi? – Peter Hosey Oct 02 '11 at 21:50
  • 1
    possible duplicate http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-iphone-sdk – Ayaz Feb 10 '14 at 09:39

3 Answers3

9

This code works for both iOS and OSX platforms, I hope.

#include <SystemConfiguration/SystemConfiguration.h>
static BOOL isInternetConnection()
{
    BOOL returnValue = NO;

#ifdef TARGET_OS_MAC

    struct sockaddr zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sa_len = sizeof(zeroAddress);
    zeroAddress.sa_family = AF_INET;

    SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr*)&zeroAddress);


#elif TARGET_OS_IPHONE

    struct sockaddr_in address;
    size_t address_len = sizeof(address);
    memset(&address, 0, address_len);
    address.sin_len = address_len;
    address.sin_family = AF_INET;

    SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithAddress(NULL, (const struct sockaddr*)&address);

#endif

    if (reachabilityRef != NULL)
    {
        SCNetworkReachabilityFlags flags = 0;

        if(SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
        {
            BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
            BOOL connectionRequired = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
            returnValue = (isReachable && !connectionRequired) ? YES : NO;
        }

        CFRelease(reachabilityRef);
    }

    return returnValue;

}
user120084
  • 184
  • 2
  • 8
8

Take a look at the SCNetworkReachability reference. This is a C API, so it's not as easy to use as a single method call, but it does a great job of notifying your app when a particular address becomes reachable or unreachable over the network.

The broad outline is you'll create an object with SCNetworkReachabilityCreateWithAddress or SCNetworkReachabilityCreateWithName, and then add it to the run loop with SCNetworkReachabilityScheduleWithRunLoop. When the reachability is determined and when it changes, the callback function you supply will be called. You can use that to update the state of your application.

Apple supplies an example app that shows how to use this (although it's designed for iOS, not Mac OS X)

Alex
  • 26,711
  • 3
  • 53
  • 74
  • Thanks a lot was interesting to know. But I need it for MAC OS. I think there should be something more simple to use. I want to check if I am connected to INternet -do Something. Like (ifConnected) {//do here } – User1234 Oct 02 '11 at 15:25
  • 2
    This is available on Mac OS X (the linked documentation is from the Mac OS X library). The example just happens to be written for iOS. There is no system-provided `isConnected` method. But you can use this to write your own `isConnected` method. – Alex Oct 02 '11 at 15:38
2

One way to do it is :

// Check whether the user has internet
- (bool)hasInternet {
    NSURL *url = [[NSURL alloc] initWithString:@"http://www.google.com"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
    BOOL connectedToInternet = NO;
    if ([NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]) {
        connectedToInternet = YES;
    }
    //if (connectedToInternet)
        //NSLog(@"We Have Internet!");
    [request release];
    [url release];
    return connectedToInternet;
}
Fatso
  • 1,190
  • 15
  • 44
  • It exactly does what I want. Thanks. – User1234 Oct 02 '11 at 16:25
  • 7
    This is a bad solution. Your application will freeze until the request succeeds or fails. This could cause your application to stall for up to 60 seconds if they have a routing problem that causes the request not to fail until the timeout is reached. Your user will not appreciate this. Even if it succeeds, the application will likely stall for several seconds, especially over a slow connection. – Alex Oct 02 '11 at 17:23
  • 1
    But what if you use NSOperation, or GCD wor this method ? I think it will work fine, and won't freeze UI. – User1234 Oct 03 '11 at 20:32
  • It is not a good practice to test connection reachability on a fixed URL like this. What can you say if Google is offline but client has internet? Additionally, this test fails in many cases where you test connection on a HTTPS url. Thumbs down for this answer. – Marcelo May 18 '15 at 16:34
  • Does this still work for countries that block Google? – Nathan Moinvaziri Jan 05 '18 at 21:54