For reasons that undoubtedly made sense at the time,1 getaddrinfo
does not report most errors via errno
, which means perror
is usually unhelpful. You have to inspect its return value as well. I shall crib from wikipedia:
err = getaddrinfo("www.example.com", NULL, NULL, &result);
if (err)
{
if (err == EAI_SYSTEM)
fprintf(stderr, "looking up www.example.com: %s\n", strerror(errno));
else
fprintf(stderr, "looking up www.example.com: %s\n", gai_strerror(err));
return -1;
}
Incidentally, be aware that there is no consensus among implementations as to what happens if you try to look up a domain name that doesn't exist or has no A or AAAA records. You might get any of EAI_NONAME
, EAI_NODATA
, EAI_FAIL
, or EAI_SYSTEM
, or you might get success but with result
set either to NULL
or to a vacuous struct addrinfo
. Yay. (For more detail on this, see https://sourceware.org/glibc/wiki/NameResolver .)
1 A lot of the newer POSIX APIs are trying to move away from errno
, which is in the abstract a good idea, but turns out to be a headache in practice because now you have to know which functions' return value is more complicated than just 0/success, -1/error.