Is there any way to capture public IP address while using mobile data and wifi in swift 4.2, I have tried IFAddress but I dint get , I am getting only local ip , but I need public ip in swift 4.2

i have used this below extension but getting only local ip

extension UIDevice {

private struct InterfaceNames {

static let wifi = ["en0"]

static let wired = ["en2", "en3", "en4"]

static let cellular = ["pdp_ip0","pdp_ip1","pdp_ip2","pdp_ip3"]

static let supported = wifi + wired + cellular

}

func ipAddress() -> String? {

var ipAddress: String?

var ifaddr: UnsafeMutablePointer<ifaddrs>?

if getifaddrs(&ifaddr) == 0 {

var pointer = ifaddr

while pointer != nil {

defer { pointer = pointer?.pointee.ifa_next }

guard

let interface = pointer?.pointee,

interface.ifa_addr.pointee.sa_family == UInt8(AF_INET),

let interfaceName = interface.ifa_name,

let interfaceNameFormatted = String(cString: interfaceName, encoding: .utf8),

InterfaceNames.supported.contains(interfaceNameFormatted)

else { continue }

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)

guard

let formattedIpAddress = String(cString: hostname, encoding: .utf8),

!formattedIpAddress.isEmpty

else { continue }

ipAddress = formattedIpAddress

break

}

freeifaddrs(ifaddr)

}

return ipAddress

}

}



// is there any native swift code to find our public ip

To start, I want to stress that the interface names hard-wired in your

InterfaceNames
structure are not considered API. Assuming that, for example,
en0
is always Wi-Fi would be a mistake. It isn’t necessary Wi-Fi on the Mac, and there have been cases where it’s not been Wi-Fi on iOS (for example, a long time ago we shipped an iPhone without Wi-Fi).

Next, the concept of a single “public IP address” doesn’t make any sense. There’s at least two problems with it:

  • It’s quite common for multiple interfaces to be on NAT networks, so the the public IP address is going to be interface-specific.

  • Even within the context of a single interface, multi-level NAT complicates the concept of a “public IP address”. The correct address to use depends on how far out you want to go in the chain of NATs.

Which brings us to the traditional question: What are you really trying to do? It’s impossible to answer this question without a better understanding of what you intend to use this value for.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Is there any way to capture public IP address while using mobile data and wifi in swift 4.2, I have tried IFAddress but I dint get , I am getting only local ip , but I need public ip in swift 4.2
 
 
Q