我需要知道当前连接的网络接口的网络接口名称,如 en0 , lo0 等等。
是否有Cocoa / Foundation功能可以提供这些信息?
答案 0 :(得分: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);
上述结构中还有许多其他标志和数据,我希望你能找到你想要的东西。
答案 1 :(得分:3)
由于iOS与OSX的工作方式略有不同,我们很幸运使用以下代码基于Davyd的答案来查看iPhone上所有可用网络接口的名称:(also see here for full documentation on ifaddrs)
#include <ifaddrs.h>
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)
{
NSString* name = [NSString stringWithUTF8String:temp_addr->ifa_name];
NSLog(@"interface name: %@", name);
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
答案 2 :(得分:0)
或者,您也可以使用if_indextoname()
获取可用的接口名称。以下是 Swift 的实现方式:
public func interfaceNames() -> [String] {
let MAX_INTERFACES = 128;
var interfaceNames = [String]()
let interfaceNamePtr = UnsafeMutablePointer<Int8>.alloc(Int(IF_NAMESIZE))
for interfaceIndex in 1...MAX_INTERFACES {
if (if_indextoname(UInt32(interfaceIndex), interfaceNamePtr) != nil){
if let interfaceName = String.fromCString(interfaceNamePtr) {
interfaceNames.append(interfaceName)
}
} else {
break
}
}
interfaceNamePtr.dealloc(Int(IF_NAMESIZE))
return interfaceNames
}
答案 3 :(得分:0)
将@ambientlight的示例代码移植到iOS 13:
▿ 20 elements
- 0 : "lo0"
- 1 : "pdp_ip0"
- 2 : "pdp_ip1"
- 3 : "pdp_ip2"
- 4 : "pdp_ip3"
- 5 : "pdp_ip5"
- 6 : "pdp_ip4"
- 7 : "pdp_ip6"
- 8 : "pdp_ip7"
- 9 : "ap1"
- 10 : "en0"
- 11 : "en1"
- 12 : "en2"
- 13 : "ipsec0"
- 14 : "ipsec1"
- 15 : "ipsec2"
- 16 : "ipsec3"
- 17 : "awdl0"
- 18 : "utun0"
- 19 : "utun1"
最有可能发生内存泄漏-请谨慎使用。
输出:
{{1}}