gethostbyname misaligned pointer

Running the following code with Undefined Behavior Sanitizer on 64-bit Mac on produces a Misaligned pointer use:


#import 
int main(void) {
  struct hostent *hp = gethostbyname2("google.com", AF_INET);
  if (hp) {
    hp->h_addr; // Misaligned pointer use on this line
  }
  return 0;
}


Is it safe to use?

I’m not 100% sure what’s going on here, but my advice is that you not use

gethostbyname
or any of the related legacy resolver cruft. In most circumstances you should use a connect-by-name API. Using the two step resolve-then-connect approach is more work and can result in slow connections in weird-o networking circumstances (for more background on this, see RFC 8305).

In the rare situations where you do need to call the resolver explicitly, you should stick with

getaddrinfo
and
getnameinfo
. These are better APIs is every conceivable way. Specifically, their interface reflects the reality of the modern Internet, that is, names can resolve to just IPv4 addresses, just IPv6 addresses, or a mixture of the two.

Share and Enjoy

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

let myEmail = "eskimo" + "1" + "@apple.com"
gethostbyname misaligned pointer
 
 
Q