tags:

views:

351

answers:

5

getaddrinfo() is a function we need to use before creating a socket() or connect()ing, right? Then how does getaddrinfo communicate with DNS server in the first place?

PS: Where can I see the complete source of getaddrinfo?

A: 

It is using DNS protocol (UDP) http://www.freesoft.org/CIE/Topics/77.htm

Zepplock
False. See Steve Emmerson's reply.
bortzmeyer
It does not? Can you prove it?
Zepplock
+2  A: 

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

getaddrinfo is a POSIX function, so there is no canonical "source"; each 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.

Tyler McHenry
+2  A: 

getaddrinfo() likely does make a connect() call behind the scenes, however it already knows the IP address of the DNS server it needs to connect to in order to query for the address of the host you are asking it to query for.

getaddrinfo() is only needed if you want to map "www.somehost.com" to an IP address, it's not needed as a primer to call connect().

You can probably find the complete source code for getaddrinfo() in glibc sources which you'd be able to find on ftp.gnu.org (among other places).

Hope that clarifies things for you.

jstedfast
caf
+1  A: 

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.

mark4o
+1  A: 

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)!

Steve Emmerson