在Swift中获取当前活动的网络适配器

时间:2017-03-19 19:02:31

标签: swift sockets networking

我使用以下代码获取macOS系统的网络适配器:

private func getAdapters() -> [Adapter]
    {
        var adapters: [Adapter] = []

        var addresses: UnsafeMutablePointer<ifaddrs>?
        guard getifaddrs(&addresses) == 0 else { return adapters }
        guard let firstAddr = addresses else { return adapters }

        for ptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next })
        {
            let address = ptr.pointee
            let rawData = address.ifa_data
            let name = address.ifa_name
            let socket: sockaddr = address.ifa_addr.pointee

            // Set up some filters
            let loopback = (address.ifa_flags & UInt32(IFF_LOOPBACK)) != 0
            let up = (address.ifa_flags & UInt32(IFF_UP)) != 0
            let p2p = (address.ifa_flags & UInt32(IFF_POINTOPOINT)) != 0

            if rawData != nil && name != nil && socket.sa_family == UInt8(AF_LINK) && !loopback && up && !p2p
            {
                let adapterName = String(utf8String: UnsafePointer<CChar>(name!))
                let adapter = Adapter(name: adapterName!)
                adapters.append(adapter)
            }
        }

        freeifaddrs(addresses)

        return adapters
    }

现在我正在寻找一种方法来弄清楚,哪些适配器是“活动”的,即哪一个连接到互联网。

我想获得网络设置中具有“绿点”的适配器。我怎样才能获得这些信息?

此致 的Sascha

0 个答案:

没有答案