如何在不使用任何使用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語法是行不通的。它通過語法錯誤。我是否需要導入任何框架試圖幫助我。
這看起來像https://stackoverflow.com/a/30754194/1187415的代碼,這已經爲斯威夫特3前段時間更新。 –