Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

macos - Convert Network Interface Name

I am trying to get a list of active network interfaces with end user understandable names. Like the names listed in System Preferences instead of en0 en5.

I have the raw interfaces using getifaddrs but haven't been able to find how to take those and get the system names of Ethernet or Wifi.

Anyone know how to do this? This would be for macOS.

What I have now:

    struct ifaddrs *ifap;
    if( getifaddrs(&ifap) == 0 ){
        struct ifaddrs *interface;

        for (interface = ifap; interface != NULL; interface = interface->ifa_next) {
            unsigned int flags = interface->ifa_flags;
            struct sockaddr *addr = interface->ifa_addr;

            // Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
            if ((flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)) {
                if (addr->sa_family == AF_INET || addr->sa_family == AF_INET6) {

                    // Convert interface address to a human readable string:
                    char host[NI_MAXHOST];
                    getnameinfo(addr, addr->sa_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST);

                    printf("interface:%s, address:%s
", interface->ifa_name, host);
                    // MAGIC HERE TO CONVERT ifa_name to "Ethernet" or something
                }

            }
        }
        freeifaddrs(ifap);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is possible with System Configuration on macOS. In Objective-C like so:

    CFArrayRef ref = SCNetworkInterfaceCopyAll();
    NSArray* networkInterfaces = (__bridge NSArray *)(ref);
    for(int i = 0; i < networkInterfaces.count; i += 1) {
        SCNetworkInterfaceRef interface = (__bridge SCNetworkInterfaceRef)(networkInterfaces[i]);

        CFStringRef displayName = SCNetworkInterfaceGetLocalizedDisplayName(interface);
        CFStringRef bsdName = SCNetworkInterfaceGetBSDName(interface);
        NSLog(@"Name:%@  
interface: %@
bsd:%@",displayName, SCNetworkInterfaceGetInterfaceType(interface), bsdName);

    }

The localized display name will be something like Display Ethernet or WiFi and the BSD name will be something like en5 which will allow matching to the above code.

This approach doesn't work on iOS, but there aren't really any other configurations on iOS anyway.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...