如何使用Cocoa或Foundation获得当前连接的网络接口名称?

问题描述 投票:2回答:4

我需要知道当前连接的网络接口的网络接口名称,如en0lo0等。

是否有可可/基础功能会向我提供此信息?

objective-c macos cocoa networking core-foundation
4个回答
9
投票

您可以循环浏览网络接口并获取其名称,IP地址等。>

#include <ifaddrs.h>
// you may need to include other headers

struct ifaddrs* interfaces = NULL;
struct ifaddrs* temp_addr = NULL;

// retrieve the current interfaces - returns 0 on success
NSInteger success = getifaddrs(&interfaces);
if (success == 0)
{
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while (temp_addr != NULL)
    {
      if (temp_addr->ifa_addr->sa_family == AF_INET) // internetwork only
      {
        NSString* name = [NSString stringWithUTF8String:temp_addr->ifa_name];
        NSString* address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
        NSLog(@"interface name: %@; address: %@", name, address);
      }

      temp_addr = temp_addr->ifa_next;
    }
}

// Free memory
freeifaddrs(interfaces);

上述结构中还有许多其他标志和数据,希望您能找到所需的内容。


3
投票

由于iOS的工作方式与OSX略有不同,我们很幸运根据达维德的答案使用以下代码来查看iPhone上所有可用网络接口的名称:(also see here for full documentation on ifaddrs


2
投票

或者,您也可以利用if_indextoname()获取可用的接口名称。这是Swift


0
投票

将@ambientlight的示例代码移植到iOS 13:

© www.soinside.com 2019 - 2024. All rights reserved.