我需要知道当前连接的网络接口的网络接口名称,如en0、lo0等。
是否有一个 Cocoa/Foundation 函数可以为我提供这些信息?
我需要知道当前连接的网络接口的网络接口名称,如en0、lo0等。
是否有一个 Cocoa/Foundation 函数可以为我提供这些信息?
您可以循环浏览网络接口并获取它们的名称、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);
上面的结构中还有很多其他的标志和数据,希望你能找到你想要的。
由于 iOS 的工作方式与 OSX 略有不同,我们很幸运地使用了基于 Davyd 的回答的以下代码来查看 iPhone 上所有可用网络接口的名称:(有关 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);
或者,您也可以利用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
}
将@ambientlight 的示例代码移植到iOS 13:
public func interfaceNames() -> [String] {
let MAX_INTERFACES = 128;
var interfaceNames = [String]()
let interfaceNamePtr = UnsafeMutablePointer<Int8>.allocate(capacity: Int(Int(IF_NAMESIZE)))
for interfaceIndex in 1...MAX_INTERFACES {
if (if_indextoname(UInt32(interfaceIndex), interfaceNamePtr) != nil){
let interfaceName = String(cString: interfaceNamePtr)
interfaceNames.append(interfaceName)
} else {
break
}
}
interfaceNamePtr.deallocate()
return interfaceNames
}
最有可能泄漏内存 - 谨慎使用。
输出:
▿ 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"