How to retrieve the device's IP address without using any third-party libraries using Swift 3 programming language? I have used the following code in order to get the IP address:
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
}
But the UnsafeMutablePointer<ifaddrs>
syntax is not working. It throws a syntax error. Do I need to import a framework to try to help me?
Add
#include<ifaddrs.h>
in your bridging header.This is the framework needed to get IP address.
Also you can refer the following link:
Swift - Get device's IP Address
try this (no bridging header is necessary, it works in Playground)
it prints on my computer
I did following things in order to get the exact IP address of the device. Since I want to include the updated code to get IP address using Swift 3, I am posting the answer here. Referred from Swift - Get device's IP Address
Add
#include<ifaddrs.h>
in your bridging headerCreate following function in order to get the IP Address.
In order to get the IP Address,
print(getIP())
For verification: -> Goto Settings -> Wi-Fi -> Click i symbol -> you can check your device IP Address.![IP Address in my iPhone](https://i.stack.imgur.com/9qo7c.png)
OUTPUT SCREENSHOT:![Output](https://i.stack.imgur.com/cAWXQ.png)