【问题标题】:Detect any connected network检测任何连接的网络
【发布时间】:2012-09-23 07:49:40
【问题描述】:

如何检测是否连接了任何网络适配器?我只能找到使用 NSReachability 检测互联网连接的示例,但我什至想检测非互联网网络连接。在 eth0 上获取 IP 地址应该可以吗?我只在 Mac 上工作。

【问题讨论】:

  • 您是在使用 iOS、Mac 还是两者兼有?
  • 好的,我只在 iPhone 上试过这个,所以我的答案可能不适用于 Mac。我会看看我是否可以做更多的研究。
  • 非常感谢。
  • 您不应依赖特定的接口名称,例如“eth0”。在 iMac 上,“en0”可以是(未连接的)以太网接口,“en1”可以是(已连接的)WiFi 接口。 Mac Pro 可以有 2 个以太网接口“en0”和“en1”。

标签: objective-c network-programming foundation


【解决方案1】:

Getting a List of All IP Addresses 在 Apple 的 技术说明 TN1145 中提到了 3 种获取网络接口状态的方法:

  • 系统配置框架
  • 开放传输 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);
}

【讨论】:

  • 非常感谢,迄今为止最好的答案。我现在没有时间尝试,但除非在接下来的 6 小时内出现更好的东西,否则我会接受它。
  • @AndreasBergström:没关系。如果有帮助,我很高兴。
【解决方案2】:

您可以使用 Apple 提供的可达性代码。 这是link,您可以在其中获得“可达性”源代码:

您也可以下载此文件:Github 中的 TestWifi。它将向您展示如何实现 Reachability 类。

希望这对你有帮助。


【讨论】:

  • 您提供的可达性链接适用于 iOS。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多