如何获得使用可可或基金会当前连接的网络接口的名字吗?(How do I get the curren

2019-07-03 15:23发布

我需要知道当前连接的网络接口的网络接口名称,如EN0,lo0等等。

有没有打算给我这个信息的可可/基础功能?

Answer 1:

您可以通过网络接口,并得到他们的名字,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);

还有许多其他的标志和数据在上面的结构,我希望你会发现你在找什么。



Answer 2:

由于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);


Answer 3:

另外,您还可以利用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
}


文章来源: How do I get the currently connected network interface name using Cocoa or Foundation?