I'm trying to convert the url to IP address during app startup by using the method gethostbyname, and in this way, let the system cache the IP address, so that in later webview and NSURLSession network requests, can skip the DNS stage and send requests directly to the IP address.
My question is, first of all, is gethostbyname safe? I see that gethostbyname is a synchronous method and may cause crash, so I put it in a background current queue and use try-catch to protect it, will this prevent crashes from happening?
Secondly, is gethostbyname the best solution to this problem? I know CFHost also has API to convert url to ip, but CFHostStartInfoResolution and CFHostGetAddressing are already marked as deprecate, is there any other solution?
I did some automation tests
I’m surprised by that result.
I have not encountered such crashes myself, but only saw other person's cases in the forum
I wouldn’t put too much stock in that thread, given the lack of details and the fact that they never responded to Matt’s request for more info.
Regardless, gethostbyname
is never the right choice. If you want to play this game — and, like endecotp, I’m skeptical about its value — you should use getaddrinfo
. It is the canonical BSD Sockets level DNS resolution API.
You will still need to call it on a secondary thread. It’s a synchronous API and synchronous networking on the main thread is never safe.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"