objective-c - 如何使用 Cocoa 或 Foundation 获取当前连接的网络接口(interface)名称?

标签 objective-c macos cocoa networking core-foundation

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

有 Cocoa/Foundation 函数可以给我这些信息吗?

最佳答案

您可以循环浏览网络接口(interface)并获取它们的名称、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);

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

关于objective-c - 如何使用 Cocoa 或 Foundation 获取当前连接的网络接口(interface)名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13279220/

相关文章:

objective-c - NSSliderCell : subclass to draw custom knob

python - 如何在 osx 上安装 pycairo?

cocoa - 如何向渐变按钮添加披露三角形?

ios - 如何从 iOS 照片库中获取图像并将其显示在 UIWebView 中

ios - reloadData 不适用于 iOS7 中的 UICollectionView

ios - UIAlertController 和 UIAlertControllerStyleActionSheet 自定义

ruby - 如何在 MacOS 上使用 "RVM --default"

macos - 如何为 Mac OS X 编写启动脚本?

ios - 指定初始化程序缺少对父类(super class)的指定初始化程序的 super 调用

c# - 监听以编程方式创建的 NSView 的事件