转换网络接口名称 [英] Convert Network Interface Name

查看:262
本文介绍了转换网络接口名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取具有最终用户可理解名称的活动网络接口的列表.类似于系统偏好设置"中列出的名称,而不是en0 en5.

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.

我有使用getifaddrs的原始接口,但无法找到如何使用它们并获取EthernetWifi的系统名称.

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.

有人知道该怎么做吗?这将适用于macOS.

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

我现在所拥有的:

    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\n", interface->ifa_name, host);
                    // MAGIC HERE TO CONVERT ifa_name to "Ethernet" or something
                }

            }
        }
        freeifaddrs(ifap);

推荐答案

在macOS上使用系统配置"可以做到这一点.在Objective-C中就像这样:

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:%@  \ninterface: %@\nbsd:%@",displayName, SCNetworkInterfaceGetInterfaceType(interface), bsdName);

    }

本地化的显示名称将类似于Display EthernetWiFi,而BSD名称将类似于en5,这将允许与上面的代码匹配.

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.

这种方法在iOS上不起作用,但iOS上实际上没有任何其他配置.

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

这篇关于转换网络接口名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆