Getting the Peer's IP Address from a nw_connection on iOS

How can I get the resolved IP address from a nw_connection?

I tried using:

Code Block objective-c
nw_endpoint_t endpoint = nw_path_copy_effective_remote_endpoint(nw_connection_copy_current_path(connection));

But that just returns the same endpoint that I provided (which was a URL + port), when I want the resolved IP address that was actually connected to.

With CFStreams I'd have gotten the file descriptor and then called getpeername().

I looked into nw_resolver_t, but that just seems to be for specifying a DoH or DoT resolver, which isn't what I want.

Answered by DTS Engineer in 653124022

I tried using

That approach works for me. Specifically, this code:

Code Block
import Foundation
import Network
func main() {
let c = NWConnection(host: "example.com", port: 80, using: .tcp)
c.stateUpdateHandler = { state in
print(state)
print(c.currentPath?.remoteEndpoint?.debugDescription ?? "-")
print("--")
}
c.start(queue: .main)
dispatchMain()
}
main()


prints this:

Code Block
preparing
example.com:80
--
ready
93.184.216.34:80
--


Once the connection is in the .ready state the remote endpoint is resolved to an IP address (which makes sense because Happy Eyeballs means that we don’t know what IP address is going to work until the TCP connection is in place).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Accepted Answer

I tried using

That approach works for me. Specifically, this code:

Code Block
import Foundation
import Network
func main() {
let c = NWConnection(host: "example.com", port: 80, using: .tcp)
c.stateUpdateHandler = { state in
print(state)
print(c.currentPath?.remoteEndpoint?.debugDescription ?? "-")
print("--")
}
c.start(queue: .main)
dispatchMain()
}
main()


prints this:

Code Block
preparing
example.com:80
--
ready
93.184.216.34:80
--


Once the connection is in the .ready state the remote endpoint is resolved to an IP address (which makes sense because Happy Eyeballs means that we don’t know what IP address is going to work until the TCP connection is in place).

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
Thank you so much Quinn!

My problem was I was calling my code from the .preparing state, rather than ready. Happy to know I was on the right track, and that it's SO much easier to get the peer IP than with CFStreams (something I also struggled with a while ago: https://stackoverflow.com/questions/55436951/how-can-i-get-the-remote-address-from-a-cfstream-in-ios)
Getting the Peer's IP Address from a nw_connection on iOS
 
 
Q