Search code examples
macoscocoaconnectionethernet

Programmatically check in OS X if there is an active ethernet connection?


How can I know my mac is connect to network by ethernet. Is there any method in cocoa which checks it?

I flung a wifi connection check, but no ethernet connection check.


Solution

  • Try like this:- First import this below framework and then write the below code

    #include <SystemConfiguration/SystemConfiguration.h> 
    
        NSString *pingHost = @"abc.apple.com"
        SCNetworkConnectionFlags flags = 0;
        if (pingHost && [pingHost length] > 0) {
            flags = 0;
            BOOL found = NO;
            SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [pingHost UTF8String]);
            if (reachabilityRef) {
                found = SCNetworkReachabilityGetFlags(reachabilityRef, &flags)
                &&  (flags & kSCNetworkFlagsReachable)
                && !(flags & kSCNetworkFlagsConnectionRequired);
                CFRelease(reachabilityRef);
                reachabilityRef = NULL;
            }
            if (found) {                
                NSLog(@"Connection established");
            }
            if (!found) {
                NSLog(@"Connection not established");
            }
        }