首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Swift Network.framework:为无IP连接的以太网接口获取NWInterface

Swift Network.framework:为无IP连接的以太网接口获取NWInterface
EN

Stack Overflow用户
提问于 2020-01-23 05:20:03
回答 1查看 516关注 0票数 2

在WWDC2019的“网络的发展”演讲中,有一个使用NWEthernetChannel监控自定义(非IP)协议的例子。这是为MacOS准备的。

代码语言:javascript
运行
复制
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连接。

EN

回答 1

Stack Overflow用户

发布于 2020-04-30 17:17:06

如果您知道其对应的BSD名称,则可以获得一个NWIntferfaceIPv4Address.init(_:)的文档中说,您可以在IP地址后指定接口名称,用%分隔。

代码语言:javascript
运行
复制
/// 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名的列表的功能。

代码语言:javascript
运行
复制
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能提供一个更好的选项来获取所有接口。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59868424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档