获取当前连接的网络接口名称

获取当前连接的网络接口名称

本文介绍了如何使用 Cocoa 或 Foundation 获取当前连接的网络接口名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道当前连接的网络接口的网络接口名称,如en0lo0等.

I need to know the network interface name of the currently connected network interface, as in en0, lo0 and so on.

是否有 Cocoa/Foundation 函数可以提供这些信息?

Is there a Cocoa/Foundation function that is going to give me this information?

推荐答案

您可以循环浏览网络接口并获取其名称、IP 地址等.

You can cycle through network interfaces and get their names, IP addresses, etc.

#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);

以上结构中还有很多其他的标志和数据,希望你能找到你想要的.

There are many other flags and data in the above structures, I hope you will find what you are looking for.

这篇关于如何使用 Cocoa 或 Foundation 获取当前连接的网络接口名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:50