Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does getaddrinfo() do DNS lookup?

Tags:

c

unix

networking

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?

like image 723
n00b2000 Avatar asked Jan 28 '10 20:01

n00b2000


People also ask

How is DNS lookup done?

A DNS lookup is initiated when an end user enters a domain name and the resolver translates it into the corresponding identifier—the IP address. To understand this process, it is best to start with the basics of DNS—what it is, how it works, and what a query journey looks like.

What does getaddrinfo do in C?

In C programming, the functions getaddrinfo() and getnameinfo() convert domain names, hostnames, and IP addresses between human-readable text representations and structured binary formats for the operating system's networking API.

How does Linux do DNS lookup?

The dig command in Linux is used to gather DNS information. It stands for Domain Information Groper, and it collects data about Domain Name Servers. The dig command is helpful for troubleshooting DNS problems, but is also used to display DNS information.

What sockets function call is used to perform a DNS lookup?

You can use the getaddrinfo() function in the socket module to perform a DNS lookup of a of a domain name, or retrieve information about a domain name or IP address.


2 Answers

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.

like image 106
mark4o Avatar answered Sep 21 '22 20:09

mark4o


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.

like image 43
Tyler McHenry Avatar answered Sep 18 '22 20:09

Tyler McHenry