2012-10-02 139 views
6

如何检测网络适配器是否连接?我只能找到使用NSReachability来检测互联网连接的例子,但我想要检测一个非互联网连接。在eth0上获得IP地址应该可以工作?我只在Mac上工作。检测任何连接的网络

+2

你是工作在iOS,Mac或两者兼而有之? – Bryan

+0

只有Mac,谢谢。 –

+0

好吧,我只在iPhone上试过这个,所以我的答案可能不适用于Mac。我会看看我是否可以做更多的研究。 – Bryan

回答

8

在苹果的技术说明TN1145提到用于获取网络接口的状态,3种方法Getting a List of All IP Addresses

  • 系统配置框架
  • 开放传输API
  • BSD套接字

系统配置框架:这是Apple推荐的方式,TN1145中有示例代码。其优点是它提供了一种获取接口配置变化通知的方法。

Open Transport API: TN1145中也有示例代码,否则我不能多说。 (Apple网站上只有“传统”文档。)

BSD套接字:这似乎是获取接口列表和确定连接状态(如果您不需要动态更改通知)。

以下代码演示如何找到所有“正在运行”的IPv4和IPv6接口。

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <ifaddrs.h> 
#include <net/if.h> 
#include <netdb.h> 

struct ifaddrs *allInterfaces; 

// Get list of all interfaces on the local machine: 
if (getifaddrs(&allInterfaces) == 0) { 
    struct ifaddrs *interface; 

    // For each interface ... 
    for (interface = allInterfaces; interface != NULL; interface = interface->ifa_next) { 
     unsigned int flags = interface->ifa_flags; 
     struct sockaddr *addr = interface->ifa_addr; 

     // Check for running IPv4, IPv6 interfaces. Skip the loopback interface. 
     if ((flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)) { 
      if (addr->sa_family == AF_INET || addr->sa_family == AF_INET6) { 

       // Convert interface address to a human readable string: 
       char host[NI_MAXHOST]; 
       getnameinfo(addr, addr->sa_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST); 

       printf("interface:%s, address:%s\n", interface->ifa_name, host); 
      } 
     } 
    } 

    freeifaddrs(allInterfaces); 
} 
+0

非常感谢,迄今为止的最佳答案。我现在没有时间去尝试,但除非在未来6小时内有更好的下降,否则我会接受。 –

+0

@AndreasBergström:没关系。如果它有帮助,我很高兴。 –

0

Reachability(我假设你的意思是基于底层SCNetworkReachability... API的Apple演示课程)适用于任何IP连接的主机,包括本地网络。您可以使用reachabilityForLocalWiFi方法,但根据this page它将在网络处于活动状态但不可路由时返回YES。所以你可能更喜欢用本地地址查询reachabilityWithAddress:

This是有人推荐的Reachability的直接替代品。

1

您可以使用Apple提供的Reachability代码。 这里的link你可以得到“可达性”的源代码:

你也可以下载这个文件:TestWifi in Github。它会告诉你如何实现Reachability类。

希望这可以帮助你。


+0

您提供的可访问性链接适用于iOS。 –