Utilities like host and dig let you see the IP address corresponding to the host name.
There is also the getent utility that can be used to query /etc/hosts or other NSS databases.
I am looking for a convenient standard utility (which is available in Debian, say) which resolves a host name regardless of where it is defined.
It should be more or less equivalent to
ping "$HOST" | head -1 | perl -lne '/((.*?))/ && print $1'
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If the problem is that you do not want to resolve these names using ipv6, then just ask getent to use ipv4 only. This will enumerate all ipv4 addresses:
<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d5a54484e584d4d587d5f515c49495c">[email protected]</a>:~$ getent ahostsv4 www.google.com | cut -d' ' -f1 | sort -u 173.194.40.80 173.194.40.81 173.194.40.82 173.194.40.83 173.194.40.84
Method 2
The thing is there are several APIs to resolve host names like gethostbyname, getaddrinfo and inet_pton and some of those can return more than one address and/or you can query the type of address you want.
If you want a portable way to get one IPv4 address, then maybe:
perl -MSocket -le 'print inet_ntoa inet_aton shift' www.google.com
Method 3
The only command that I am aware that does what you want is resolveip:
http://linux.die.net/man/1/resolveip
However it only comes with mysql-server, which may not be ideal to install everywhere.
Method 4
gethostip -d name.domain from the syslinux package on Ubuntu (and probably Debian). -d outputs decimal format.
Method 5
(This answer only applies if you’re root on the machine.)
I used to be annoyed by this too, and then I standardized on running dnsmasq on all my machines. Dnsmasq is a lightweight DNS cache. As a side benefit, it serves the content of /etc/hosts over DNS.
Method 6
I used my pure perl knowledge and made a little script with error handling:
/usr/local/bin/gethostip:
#!/usr/bin/perl
# inspired by: https://unix.stackexchange.com/questions/71379/host-lookup-that-respects-etc-hosts#71393
use strict;
use Socket;
my $name = $ARGV[0];
if ($name eq '') {
print STDERR "Usage: gethostip <hostname>n";
exit 1;
}
my $ip = inet_aton($name);
die("Unable to resolve host name $name") if ($ip eq '');
my $ipstr = inet_ntoa($ip);
print "$ipstrn";
Thx to Stéphane Chazelas for the initial idea
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0