使用 getifaddrs() 在 Swift 中找不到 Thunderbolt 到以太网适配器
Thunderbolt to Ethernet adapter not found in Swift using getifaddrs()
我有以下代码来获取我的 MacBook 上所有适配器的列表:
if getifaddrs(&addresses) == 0
{
let buffer = UnsafeBufferPointer(start: addresses, count: 16)
for address in buffer
{
let rawData = address.ifa_data
let name = address.ifa_name
let socket: sockaddr = address.ifa_addr.pointee
if rawData != nil && name != nil && socket.sa_family == UInt8(AF_LINK)
{
let adapterName = String(utf8String: UnsafePointer<CChar>(name!))
let adapter = Adapter(name: adapterName!)
adapters.append(adapter)
}
}
}
代码运行良好,(几乎)所有适配器都已返回。如果使用 Thunderbolt 转以太网适配器,则不会返回此网络。
我怎样才能得到这个适配器?
您的代码假定 getifaddrs()
returns 是 struct ifaddrs
的 数组 ,但事实并非如此。该函数存储对a的引用
给定地址的链表,ifa_next
成员指向
到下一个元素(或 nil
最后一个元素)。
下面是一个如何遍历列表和存储接口的例子
将名称放入数组中(How to get Ip address in swift 中代码的修改):
func getInterfaceNames() -> [String] {
var names = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return [] }
guard let firstAddr = ifaddr else { return [] }
// For each interface ...
for ptr in sequence(first: firstAddr, next: { [=10=].pointee.ifa_next }) {
let addr = ptr.pointee.ifa_addr.pointee
if addr.sa_family == UInt8(AF_LINK) {
let name = String(cString: ptr.pointee.ifa_name)
names.append(name)
}
}
return names
}
在我的 iMac 上,这给出了
["lo0", "gif0", "stf0", "en1", "en2", "en3", "p2p0", "awdl0", "en0", "bridge0", "utun0"]
包括 "bridge0" 用于 Thunderbolt 网桥,而您的代码
只有 returns
"lo0", "gif0", "stf0", "en1"
我有以下代码来获取我的 MacBook 上所有适配器的列表:
if getifaddrs(&addresses) == 0
{
let buffer = UnsafeBufferPointer(start: addresses, count: 16)
for address in buffer
{
let rawData = address.ifa_data
let name = address.ifa_name
let socket: sockaddr = address.ifa_addr.pointee
if rawData != nil && name != nil && socket.sa_family == UInt8(AF_LINK)
{
let adapterName = String(utf8String: UnsafePointer<CChar>(name!))
let adapter = Adapter(name: adapterName!)
adapters.append(adapter)
}
}
}
代码运行良好,(几乎)所有适配器都已返回。如果使用 Thunderbolt 转以太网适配器,则不会返回此网络。
我怎样才能得到这个适配器?
您的代码假定 getifaddrs()
returns 是 struct ifaddrs
的 数组 ,但事实并非如此。该函数存储对a的引用
给定地址的链表,ifa_next
成员指向
到下一个元素(或 nil
最后一个元素)。
下面是一个如何遍历列表和存储接口的例子 将名称放入数组中(How to get Ip address in swift 中代码的修改):
func getInterfaceNames() -> [String] {
var names = [String]()
// Get list of all interfaces on the local machine:
var ifaddr : UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&ifaddr) == 0 else { return [] }
guard let firstAddr = ifaddr else { return [] }
// For each interface ...
for ptr in sequence(first: firstAddr, next: { [=10=].pointee.ifa_next }) {
let addr = ptr.pointee.ifa_addr.pointee
if addr.sa_family == UInt8(AF_LINK) {
let name = String(cString: ptr.pointee.ifa_name)
names.append(name)
}
}
return names
}
在我的 iMac 上,这给出了
["lo0", "gif0", "stf0", "en1", "en2", "en3", "p2p0", "awdl0", "en0", "bridge0", "utun0"]
包括 "bridge0" 用于 Thunderbolt 网桥,而您的代码 只有 returns
"lo0", "gif0", "stf0", "en1"