When you call ping name.domain, it goes through both /etc/hosts and the DNS resolver to obtain an IP. It could be an IP hard-coded in /etc/hosts, or it could be one from the DNS server. It does so by calling getaddrinfo() or equivalent, not directly, of course.How do I call getaddrinfo() from shell? How do I reproduce the effect of normal net utilities to obtain an IP from an address?This is not about using dig/host which only go through DNS, or getent which only goes through hosts. I want to reproduce common application behavior (e.g. ping) when it receives a name it needs to resolve. There are other questions about dig/host. This question is not a duplicate of those.Update: here are my findings (based partly on answers to other Qs)on Ubuntu (and Debian?) there is gethostip -d name.domain from syslinux.perl -MSocket -le 'print inet_ntoa inet_aton shift' name.domain works reliably and is terser than the accepted answer.Using getent may also work: getent ahostsv4 name.domain | grep STREAM | head -1 | cut -f1 -d' 'This seems to be the best one can do.
getaddrinfo() from shell?
shell;networking;dns
If you have access to Perl I rolled my own (well found it on the internet and used it):#!/usr/bin/perluse Socket;$host = shift @ARGV;die(usage: gethostbyname hostname\n) unless(defined($host));$packed_ip = gethostbyname($host);if (defined $packed_ip) {    $ip_address = inet_ntoa($packed_ip);    print $ip_address\n;    exit 0} else {    warn $host not found\n;    exit 1}This code comes from this SF Q&A titled: Linux command line utility to resolve host names using /etc/hosts first.Examples$ ./gethostbyname.pl skinner192.168.1.3$ ./gethostbyname.pl www.google.com74.125.225.84$ ./gethostbyname.pl localhost127.0.0.1I've used the above method when code was running on multiple Unix machines, not just Linux, and so getent wasn't an option.getentI know the man page for getent leaves you thinking that getent will only look in the file databases, but I believe it goes through whatever means are defined in /etc/nsswitch.conf. So if it states dns as a value there, then I believe it will interrogate the DNS server that's configured in /etc/resolv.conf. Assuming there is one defined in that file.In my testing I do not have an entry in my file, /etc/hosts, for the host skinner and yet getent resolves it just fine via DNS.$ getent hosts skinner192.168.1.3     skinner.bubba.net$ grep skinner /etc/hosts$