使用getifaddrs()在Swift中找不到Thunderbolt到以太网适配器

时间:2016-11-19 17:11:56

标签: swift networking network-interface

我有以下代码来获取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 to Ethernet适配器,则不会返回此网络。

如何获得此适配器?

1 个答案:

答案 0 :(得分:1)

您的代码假定getifaddrs()返回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: { $0.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"]

包括Thunderbolt桥的“bridge0”,而你的代码 只返回

"lo0", "gif0", "stf0", "en1"