gpt4 book ai didi

objective-c - 检测任何连接的网络

转载 作者:太空狗 更新时间:2023-10-30 03:41:57 26 4
gpt4 key购买 nike

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

最佳答案

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

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

System Configuration Framework:这是Apple推荐的方式,在TN1145中有示例代码。优点是它提供了一种获取接口(interface)配置更改通知的方法。

Open Transport API:TN1145中也有样例代码,不然我就不多说了。 (Apple 网站上只有“遗留”文档。)

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

以下代码演示了如何查找“已启动并正在运行”的所有 IPv4 和 IPv6 接口(interface)。

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

关于objective-c - 检测任何连接的网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12690622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com