我需要知道当前连接的网络接口(interface)的网络接口(interface)名称,如en0、lo0等。
有 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/