2017-07-30 74 views
1

函數總是返回零,如果我打印接口的名字裏有沒有名字「EN0」。我需要獲取設備的本地ipaddress,我該如何做?函數getWiFiAddress()總是返回nil?

func getWiFiAddress() -> String? { 
var address : String? 

// Get list of all interfaces on the local machine: 
var ifaddr : UnsafeMutablePointer<ifaddrs>? 
guard getifaddrs(&ifaddr) == 0 else { return nil } 
guard let firstAddr = ifaddr else { return nil } 

// For each interface ... 
for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { 
    let interface = ifptr.pointee 

    // Check for IPv4 or IPv6 interface: 
    let addrFamily = interface.ifa_addr.pointee.sa_family 
    if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { 

     // Check interface name: 
     let name = String(cString: interface.ifa_name) 
     if name == "en0" { 

      // Convert interface address to a human readable string: 
      var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) 
      getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), 
         &hostname, socklen_t(hostname.count), 
         nil, socklen_t(0), NI_NUMERICHOST) 
      address = String(cString: hostname) 
     } 
    } 
} 
freeifaddrs(ifaddr) 

return address 

}

回答

0

您沒有設置任何值ifaddr的。

0

,而不是EN0我改成了EN1和它得到我的本地IP地址....原因是EN0是有線或以太網,無線,我們需要使用EN1。

0

您需要使用

lo0的

對於本地地址不

func getWiFiAddress() -> String? { 
    // Get list of all interfaces on the local machine: 
    var ifaddr : UnsafeMutablePointer<ifaddrs>? 
    guard getifaddrs(&ifaddr) == 0 else { return nil } 
    guard let firstAddr = ifaddr else { return nil } 

    // For each interface ... 
    for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { 
     let interface = ifptr.pointee 

     // Check for IPv4 or IPv6 interface: 
     let addrFamily = interface.ifa_addr.pointee.sa_family 
     if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { 

      // Check interface name: 
      let name = String(cString: interface.ifa_name) 
      if name == "lo0" { 

       // Convert interface address to a human readable string: 
       var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) 
       getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), 
          &hostname, socklen_t(hostname.count), 
          nil, socklen_t(0), NI_NUMERICHOST) 
       freeifaddrs(ifaddr) 
       return String(cString: hostname) 
      } 
     } 
    } 
    return nil 
} 
+0

lo0的是環回接口......如果我們需要得到本地局域網IP,我們需要使用en0用於有線網絡,en1用於無線... –