How to determine your internet connection in Cocoa?

I need to determine if an internet connection is available or not. I don’t care how it is connected (WIFI, Lan, etc.). I need to determine if an internet connection is available.

PS I found a way to check the WIFI connection. But I don’t care how it is connected (I need to check all the ways to connect to the Internet).

Something like (isConnected)

+5
source share
3 answers

Take a look at the SCNetworkReachabilitylink. This is a C API, so it is not as easy to use as a single method call, but it does a great job of notifying your application when a particular address becomes available or inaccessible over the network.

SCNetworkReachabilityCreateWithAddress SCNetworkReachabilityCreateWithName, SCNetworkReachabilityScheduleWithRunLoop. , . , .

Apple , , ( iOS, Mac OS X)

+8

iOS, OSX. .

#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;

}
+7

:

// 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;
}
+3

All Articles