如何在 iOS 和 Mac OS X 上查找接口的硬件类型



我正在编写一些代码,启发式地计算出服务位于网络接口上的可能性。我正在寻找的硬件没有实现 SSDP 或 mDNS,所以我必须手动查找它。

该设备通过WiFi

连接到网络,因此我很可能会通过WiFi接口找到它。但是,Mac可以通过以太网连接到WiFi网桥,因此很可能可以通过以太网解决。

为了避免不必要的请求并通常成为一个良好的网络公民,我想明智地决定首先尝试哪个接口。

我可以毫无问题地获取计算机上的接口列表,但这没有帮助:en0我的iMac上是有线以太网,但Macbook上的WiFi。

如果这也适用于 iOS,则加分,因为尽管很少见,但您可以将 USB 以太网适配器与它一起使用。

使用 SystemConfiguration 框架:

import Foundation
import SystemConfiguration
for interface in SCNetworkInterfaceCopyAll() as NSArray {
    if let name = SCNetworkInterfaceGetBSDName(interface as! SCNetworkInterface),
       let type = SCNetworkInterfaceGetInterfaceType(interface as! SCNetworkInterface) {
            print("Interface (name) is of type (type)")
    }
}

在我的系统上,这将打印:

Interface en0 is of type IEEE80211
Interface en3 is of type Ethernet
Interface en1 is of type Ethernet
Interface en2 is of type Ethernet
Interface bridge0 is of type Bridge

不是 Mac 开发人员,但在iOS上我们可以使用 Apple 提供的 Reachability 类。

Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if(status == NotReachable) 
{
    //No Connection
}
else if (status == ReachableViaWiFi)
{
    //WiFi Connection
}
else if (status == ReachableViaWWAN) 
{
    //Carrier Connection
}

直接进入C:(作为奖励获得IP)

@implementation NetworkInterfaces
+(void)display{
    struct ifaddrs *ifap, *ifa;
    struct sockaddr_in *sa;
    char *addr;
    getifaddrs (&ifap);
    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr->sa_family==AF_INET) {
            sa = (struct sockaddr_in *) ifa->ifa_addr;
            addr = inet_ntoa(sa->sin_addr);
            printf("Interface: %stAddress: %sn", ifa->ifa_name, addr);
        }
    }
    freeifaddrs(ifap);
}
@end

在控制器(或应用程序委托)中:

(斯威夫特)

NetworkInterfaces.display()

(objC) [网络接口显示];

最新更新