Hey everyone,
I’m developing an app for visionOS where I need to display the Apple Vision Pro’s current IP address. For this I’m using the following code, which works for iOS, macOS, and visionOS in the simulator. Only on a real Apple Vision Pro it’s unable to extract an IP. Could it be that visionOS currently doesn’t allow this? Have any of you had the same experience and found a workaround?
var address: String = "no ip"
var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil
if getifaddrs(&ifaddr) == 0 {
var ptr = ifaddr
while ptr != nil {
defer { ptr = ptr?.pointee.ifa_next }
let interface = ptr?.pointee
let addrFamily = interface?.ifa_addr.pointee.sa_family
if addrFamily == UInt8(AF_INET) {
if let name: Optional<String> = String(cString: (interface?.ifa_name)!), name == "en0" {
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)
address = String(cString: hostname)
}
}
}
freeifaddrs(ifaddr)
}
return address
}
Thanks in advance for any insights or tips!
Best Regards,
David
I’ve not actually tried to do this on an Apple Vision Pro, but your code is definitely wonky because there’s no guarantee that en0
is the primary Wi-Fi interface. That’s true on iOS as well, and code like this is known to fail in weird edge cases on that platform. And on macOS those failing cases aren’t even edge cases, but happen all the time.
As to what you should do, lemme start you out with my Don’t Try to Get the Device’s IP Address post. This outlines a bunch of common scenarios and the best path forward in each case. If you’re use case isn’t covered there, reply back here with more details about what you’re doing and we can explore your options.
This is part of my Extra-ordinary Networking series, and the rest of the folks in that series offer important background to this issue.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"