The POSIX getaddrinfo()
function is used to perform DNS resolution, as well as service name resolution. The hints
argument passed to getaddrinfo()
has a flags field, ai_flags
.
Among the possible flag values is AI_NUMERICHOST
. According to the documentation, this informs getaddrinfo()
that the hostname string is an IP address. Since the hostname is already an IP address (as opposed to a hostname), no DNS resolution is necessary.
I'm having trouble understanding the purpose or use-case of this flag. If you already have the IP address, why would you even need to call getaddrinfo()
? The only possible purpose I could see would be a case where you already have the IP address, but just want to get the service name. But in that case, you could just call getservbyname()
directly, which would be much simpler.
The only thing I can think of is that getaddrinfo()
is re-entrant, whereas apparently getservbyname()
is not re-entrant. So is the entire purpose of the AI_NUMERICHOST
flag simply to provide a round-about way of doing a thread-safe getservbyname()
?
If not, what is the purpose of AI_NUMERICHOST
?
The primary use of getaddrinfo
with AI_NUMERICHOST
is to be an IPv4/IPv6-agnostic replacement for inet_aton
and inet_pton
. That is, it takes textual IPv4 and IPv6 addresses and converts them to sockaddr
objects; calling code doesn't have to know which is which.
It's also true that you can use it as a thread-safe getservbyname
, but I can't recall the last time I saw code that didn't use AI_NUMERICSERV
, so I don't think that's the important property.