在WWDC2019的“网络的发展”演讲中,有一个使用NWEthernetChannel
监控自定义(非IP)协议的例子。这是为MacOS准备的。
import Foundation
import Network
let path = NWPathMonitor(requiredInterfaceType: .wiredEthernet).currentPath
guard let interface = path.availableInterfaces.first else {
fatalError("not connected to Internet")
}
let channel = NWEthernetChannel(on: interface, etherType: 0xB26E)
对于我的应用程序,我需要使用NWEthernetChannel
来监控以太网链路上的自定义协议(实际上是思科发现协议和/或链路层发现协议),该以太网链路没有IP互联网连接(但它具有到交换机的物理链路)。NWPath似乎只给我一个NWInterface结构,如果它是一个有效的互联网路径。
如果没有有效的NWInterface
路径,我如何获取Mac上的互联网结构列表?
在我的特定用例中,我只对.wiredEthernet.
感兴趣
像在一个盒子上获得所有NWInterfaces
的完整阵列这样简单的事情就足够了,但到目前为止,我发现的唯一“出售”NWInterfaces
的方法是使用NWPathMonitor
,这似乎需要IP连接。
发布于 2020-04-30 17:17:06
如果您知道其对应的BSD名称,则可以获得一个NWIntferface
。IPv4Address.init(_:)
的文档中说,您可以在IP地址后指定接口名称,用%
分隔。
/// Create an IP address from an address literal string.
/// If the string contains '%' to indicate an interface, the interface will be
/// associated with the address, such as "::1%lo0" being associated with the loopback
/// interface.
/// This function does not perform host name to address resolution. This is the same as calling getaddrinfo
/// and using AI_NUMERICHOST.
您只能在生成的swift界面中找到此文档,而不能在网站上找到。
SystemConfiguration
框架提供了获取所有接口及其对应的BSD名的列表的功能。
import Foundation
import Network
import SystemConfiguration
// get all interfaces
let interfaces = SCNetworkInterfaceCopyAll() as? Array<SCNetworkInterface> ?? []
// convert to NWInterface
let nwInterfaces = interfaces.compactMap { interface -> NWInterface? in
guard let bsdName = SCNetworkInterfaceGetBSDName(interface) else { return nil }
return IPv4Address("127.0.0.1%\(bsdName)")?.interface
}
print(interfaces)
这很好用,但感觉像是一种变通方法。我希望Network.framework能提供一个更好的选项来获取所有接口。
https://stackoverflow.com/questions/59868424
复制相似问题