2

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)

对于我的应用程序,我需要使用 aNWEthernetChannel来监控没有 IP Internet 连接(但它确实有到交换机的物理链路)的以太网链路上的自定义协议(实际上是 Cisco 发现协议和/或链路层发现协议)。如果 NWPath 是通往 Internet 的有效路径,NWPath 似乎只会给我一个 NWInterface 结构。

如何NWInterface在没有有效 Internet 路径的情况下获取 Mac 上的结构列表?

在我的特定用例中,我只对.wiredEthernet.

NWInterfaces在一个盒子上得到一个完整的数组这样简单的东西就足够了,但到目前为止,NWInterfaces我发现“出售”的唯一方法是 with NWPathMonitor,这似乎需要 IP 连接。

4

1 回答 1

2

NWIntferface如果您知道其对应的 BSD 名称,您可以获得一个。的文档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 能够提供更好的选择来获取所有接口。

于 2020-04-30T09:17:05.537 回答