And*_*röm 6 network-programming objective-c foundation
如何检测是否连接了任何网络适配器?我只能找到使用NSReachability来检测互联网连接的例子,但我想检测一个非互联网网络连接.获取eth0的IP地址应该有效吗?我只在Mac上工作.
获取 Apple 技术说明中的所有IP地址列表TN1145提到了3种获取网络接口状态的方法:
系统配置框架:这是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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4516 次 |
| 最近记录: |