How does getaddrinfo() do DNS lookup? How does getaddrinfo() do DNS lookup? unix unix

How does getaddrinfo() do DNS lookup?


It is not necessary to call getaddrinfo() before creating a socket or connecting. It is used to translate a domain name, like stackoverflow.com, to an IP address like 69.59.196.211. If you know the IP address then you can connect directly to that address and there is no need to use getaddrinfo(). getaddrinfo() uses the DNS protocol to talk to your name servers, which are configured using their IP address.

The glibc source code is here.


The short answer is "it asks the system", which in turn knows how to do DNS lookups and which servers to use.

getaddrinfo() is documented by the getaddrinfo(3) manual page, which means it's a C library function. It is also a POSIX function, so there is no canonical "source"; each standard C library of an operating system that conforms to POSIX will implement its own version. Either way the source to just that function is probably not too enlightening, since it would just call other functions and OS APIs, and you'd have to drill down pretty far to get to the actual DNS mechanism. You'd be better off reading documentation of the DNS protocol itself if you're interested in how that works.


Does your Unix system have the file /etc/nsswitch.conf? If so, then the "hosts" entry gives the search order for resolving hostnames into IP addresses. Does your system have the file /etc/resolv.conf? If so, then it specifies what DNS servers to use.

As you can see, getaddrinfo() can do quite a bit (and can take a while)!