2012-10-02 106 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。 –