WWDC2019 的“网络进展”演讲中有一个使用 NWEthernetChannel
监控自定义(非 IP)协议(protocol)的示例。这是针对 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 Internet 连接的以太网链路上的自定义协议(protocol)(实际上是思科发现协议(protocol)和/或链路层发现协议(protocol))(但它确实有到交换机的物理链接)。如果 NWPath 是通往 Internet 的有效路径,则 NWPath 似乎只会给我一个 NWInterface 结构。
如何在没有有效 Internet 路径的情况下获取 Mac 上的 NWInterface
结构列表?
在我的特定用例中,我只对 .wiredEthernet 感兴趣。
像在盒子上获取所有NWInterfaces
的完整数组这样简单的事情就足够了,但到目前为止,我发现“出售”NWInterfaces
的唯一方法与NWPathMonitor
一起使用,它似乎需要IP连接。
最佳答案
如果您知道其对应的 BSD 名称,则可以获得 NWIntferface
。
IPv4Address.init(_:)
的文档说你可以指定
IP 地址后的接口(interface),以 %
分隔。
/// 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接口(interface),而不是在网站上找到此文档。
SystemConfiguration
框架提供了获取所有接口(interface)及其相应 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 能够提供更好的选择来获取所有接口(interface)。
关于 swift 网络.framework : get NWInterface for ethernet interface without IP connectivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868424/