我需要知道當前連接的網絡接口的網絡接口名稱,如en0,lo0等等。如何使用Cocoa或Foundation獲取當前連接的網絡接口名稱?
是否有一個Cocoa/Foundation函數可以給我這些信息?
我需要知道當前連接的網絡接口的網絡接口名稱,如en0,lo0等等。如何使用Cocoa或Foundation獲取當前連接的網絡接口名稱?
是否有一個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的名稱:(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);
或者你也可以利用if_indextoname()
獲取可用的接口名稱。這裏是斯威夫特實施會是什麼樣子:
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
}
尼斯,將檢查了這一點,這裏報到。 –