Search code examples
iosiphoneipadswift3ip-address

Get IPAddress of iPhone or iPad device Using Swift 3


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?


Solution

  • 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