iKenndac
iKenndac

Reputation: 18776

How to find the hardware type of an interface on iOS and Mac OS X?

I'm writing some code that heuristically figures out the likelihood of a service being on a network interface. The hardware I'm searching for doesn't implement SSDP or mDNS, so I have to look for it manually.

The device connects to the network via WiFi, so it's most likely that I'll find it over the WiFi interface. However, it's possible for the Mac to be connected to a WiFi bridge via Ethernet, so it may well be resolvable through that.

To avoid unnecessary requests and to be generally a good network citizen, I'd like to be intelligent about which interface to try first.

I can get the list of interfaces on my computer no problem, but that's not helpful: en0 is wired ethernet on my iMac, but WiFi on my Macbook.

Bonus points if this works on iOS as well, since although it's rare you can use the USB Ethernet adapter with it.

Upvotes: 6

Views: 2673

Answers (3)

ingconti
ingconti

Reputation: 11646

go straight in C: (as a bonus get IP)

@implementation NetworkInterfaces

+(void)display{
    struct ifaddrs *ifap, *ifa;
    struct sockaddr_in *sa;
    char *addr;

    getifaddrs (&ifap);
    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr->sa_family==AF_INET) {
            sa = (struct sockaddr_in *) ifa->ifa_addr;
            addr = inet_ntoa(sa->sin_addr);
            printf("Interface: %s\tAddress: %s\n", ifa->ifa_name, addr);
        }
    }

    freeifaddrs(ifap);
}
@end

in controller (or AppDelegate):

(swift)

NetworkInterfaces.display()

(objC) [NetworkInterfaces display];

Upvotes: 0

eelco
eelco

Reputation: 1607

Use the SystemConfiguration framework:

import Foundation
import SystemConfiguration

for interface in SCNetworkInterfaceCopyAll() as NSArray {
    if let name = SCNetworkInterfaceGetBSDName(interface as! SCNetworkInterface),
       let type = SCNetworkInterfaceGetInterfaceType(interface as! SCNetworkInterface) {
            print("Interface \(name) is of type \(type)")
    }
}

On my system, this prints:

Interface en0 is of type IEEE80211
Interface en3 is of type Ethernet
Interface en1 is of type Ethernet
Interface en2 is of type Ethernet
Interface bridge0 is of type Bridge

Upvotes: 8

quant24
quant24

Reputation: 392

Not much of a Mac developer, but on iOS we can use the Reachability class provided by Apple.

Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];

NetworkStatus status = [reachability currentReachabilityStatus];

if(status == NotReachable) 
{
    //No Connection
}
else if (status == ReachableViaWiFi)
{
    //WiFi Connection
}
else if (status == ReachableViaWWAN) 
{
    //Carrier Connection
}

Upvotes: 0

Related Questions