kamesh bala kamesh bala -3 years ago 89
iOS Question

Get IPAddress of iPhone or iPad device Using Swift 3

How to get the device IP Address without using any third party libraries using Swift 3 programming language. Actually I have used 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 syntax is not working. It throughs syntax error. Do I need to import any framework try to help me.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download