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 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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With