gpt4 book ai didi

Swift Network.framework : get NWInterface for ethernet interface without IP connectivity

转载 作者:行者123 更新时间:2023-12-04 10:42:26 25 4
gpt4 key购买 nike

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)(实际上是 Cisco 发现协议(protocol)和/或链路层发现协议(protocol))。如果 NWPath 是通往 Internet 的有效路径,NWPath 似乎只会给我一个 NWInterface 结构。

如何获得 NWInterface 的列表Mac 上的结构没有有效的 Internet 路径?

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

像获取所有 NWInterfaces 的完整数组一样简单的事情在一个盒子上就足够了,但到目前为止,“贩卖”的唯一方法 NWInterfaces我发现是 NWPathMonitor ,这似乎需要IP连接。

最佳答案

你可以得到一个NWIntferface如果你知道它对应的 BSD 名称。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 界面中找到此文档,而不是在网站上。
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 Network.framework : get NWInterface for ethernet interface without IP connectivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com