2017-06-14 148 views
1

如何在不使用任何使用Swift 3編程語言的第三方庫的情況下獲取設備IP地址。其實我已經使用下面的代碼來獲取IP地址。獲取iPhone或iPad設備的IP地址使用Swift 3

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

var ifaddr : UnsafeMutablePointer<ifaddrs> = nil 
if getifaddrs(&ifaddr) == 0 { 

    var ptr = ifaddr 
    while ptr != nil { 
     defer { ptr = ptr.memory.ifa_next } 

     let interface = ptr.memory 

     let addrFamily = interface.ifa_addr.memory.sa_family 
     if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { 

      if let name = String.fromCString(interface.ifa_name) where name == "en0" { 

       var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0) 
       getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.memory.sa_len), 
          &hostname, socklen_t(hostname.count), 
          nil, socklen_t(0), NI_NUMERICHOST) 
       address = String.fromCString(hostname) 
      } 
     } 
    } 
    freeifaddrs(ifaddr) 
} 

return address 

}

但UnsafeMutablePointer語法是行不通的。它通過語法錯誤。我是否需要導入任何框架試圖幫助我。

+0

這看起來像https://stackoverflow.com/a/30754194/1187415的代碼,這已經爲斯威夫特3前段時間更新。 –

回答

0

在橋接頭中添加#include<ifaddrs.h>

這是獲取IP地址所需的框架。

您也可以參考以下鏈接:

Swift - Get device's IP Address

+0

根本沒有必要..還有其他可能性如何獲得所有接口的所有IP4/IP6地址所需的信息。看到我的答案。 – user3441734

1

試試這個(無橋接報是必要的,在遊樂場它作品)

//: Playground - noun: a place where people can play 

import Darwin 

var temp = [CChar](repeating: 0, count: 255) 
enum SocketType: Int32 { 
    case SOCK_STREAM = 0, SOCK_DGRAM, SOCK_RAW 
} 

// host name 
gethostname(&temp, temp.count) 
// create addrinfo based on hints 
// if host name is nil or "" we can connect on localhost 
// if host name is specified (like "computer.domain" ... "My-MacBook.local") 
// than localhost is not aviable. 
// if port is 0, bind will assign some free port for us 

var port: UInt16 = 0 
let hosts = ["localhost", String(cString: temp)] 
var hints = addrinfo() 
hints.ai_flags = 0 
hints.ai_family = PF_UNSPEC 

for host in hosts { 
    print("\n\(host)") 
    print() 

    // retrieve the info 
    // getaddrinfo will allocate the memory, we are responsible to free it! 
    var info: UnsafeMutablePointer<addrinfo>? 
    defer { 
     if info != nil 
     { 
      freeaddrinfo(info) 
     } 
    } 
    var status: Int32 = getaddrinfo(host, String(port), nil, &info) 
    guard status == 0 else { 
     print(errno, String(cString: gai_strerror(errno))) 
     continue 
    } 
    var p = info 
    var i = 0 
    var ipFamily = "" 
    var ipType = "" 
    while p != nil { 
     i += 1 
     // use local copy of info 
     var _info = p!.pointee 
     p = _info.ai_next 

     switch _info.ai_family { 
     case PF_INET: 
      _info.ai_addr.withMemoryRebound(to: sockaddr_in.self, capacity: 1, { p in 
       inet_ntop(AF_INET, &p.pointee.sin_addr, &temp, socklen_t(temp.count)) 
       ipFamily = "IPv4" 
      }) 
     case PF_INET6: 
      _info.ai_addr.withMemoryRebound(to: sockaddr_in6.self, capacity: 1, { p in 
       inet_ntop(AF_INET6, &p.pointee.sin6_addr, &temp, socklen_t(temp.count)) 
       ipFamily = "IPv6" 
      }) 
     default: 
      continue 
     } 
     print(i,"\(ipFamily)\t\(String(cString: temp))", SocketType(rawValue: _info.ai_socktype)!) 

    } 

} 

它打印在我電腦

localhost 

1 IPv6 ::1 SOCK_RAW 
2 IPv6 ::1 SOCK_DGRAM 
3 IPv4 127.0.0.1 SOCK_RAW 
4 IPv4 127.0.0.1 SOCK_DGRAM 

Ivos-MacBook-Pro.local 

1 IPv6 fe80::18a2:e892:fbd7:558e SOCK_RAW 
2 IPv6 fe80::18a2:e892:fbd7:558e SOCK_DGRAM 
3 IPv4 172.20.10.3 SOCK_RAW 
4 IPv4 172.20.10.3 SOCK_DGRAM 
+0

不錯,爲我工作,純粹Swift 3 – DwarDoh

+0

以上iOS 10和模擬器。沒有在iPad 2和iOS 9上工作。對於IPv4,只返回本地主機信息127.0.0.1,而不是設備的,並且這個msg:「warning:無法執行支持代碼來讀取進程中的Objective-C類數據。可用類型信息的質量「。 – DwarDoh

+0

iPhone 6,iOS 10上的同樣問題。沒有設備IP返回。獲取此信息:「警告:在主線程上調用mDNSResponder的Libinfo 0未知錯誤 警告:無法執行支持代碼來讀取進程中的Objective-C類數據,這可能會降低可用類型信息的質量。 – DwarDoh

2

我做了以下事情以獲取設備的確切IP地址。由於我想包含更新後的代碼以使用Swift 3獲取IP地址,因此我在此發佈答案。在你的橋接報從Swift - Get device's IP Address

  1. 簡稱添加#include<ifaddrs.h>

  2. ,以獲取IP地址創建下面的函數。

    func getIP()-> String? { 
    
    var address: String? 
    var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil 
    if getifaddrs(&ifaddr) == 0 { 
    
        var ptr = ifaddr 
        while ptr != nil { 
         defer { ptr = ptr?.pointee.ifa_next } // memory has been renamed to pointee in swift 3 so changed memory to pointee 
    
         let interface = ptr?.pointee 
         let addrFamily = interface?.ifa_addr.pointee.sa_family 
         if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { 
    
          if let name: String = String(cString: (interface?.ifa_name)!), name == "en0" { // String.fromCString() is deprecated in Swift 3. So use the following code inorder to get the exact IP Address. 
           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 
    } 
    
  3. 爲了獲得IP地址,print(getIP())

爲了驗證: - >轉到設置 - >無線網絡 - >點擊我的象徵 - >您可以檢查您的設備IP地址。 IP Address in my iPhone

輸出截圖:Output