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

Mau*_*res 2 macos networking cocoa objective-c core-foundation

我需要知道当前连接的网络接口的网络接口名称,如en0,lo0等.

是否有Cocoa/Foundation功能可以提供这些信息?

Dav*_*eyl 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);
Run Code Online (Sandbox Code Playgroud)

上述结构中还有许多其他标志和数据,我希望你能找到你想要的东西.