2016-11-19 70 views
0

我有以下的代碼來獲取我的MacBook上的所有適配器列表getifaddrs()在雨燕未發現:迅雷以太網適配器使用

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適配器,則不會返回此網絡。

如何獲得此適配器?

回答

0

你的代碼假設getifaddrs()返回一個數組struct ifaddrs,這是不正確的。該功能存儲對給定地址的 鏈接列表的引用,其中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" 
+0

謝謝,我會試試。 –