2

This question already has an answer here:

host, dig and nslookup can be used to lookup DNS names from the command line. However, they query the names from the DNS server directly, instead of using nsswitch to resolve host names. This means /etc/hosts and mDNS aren't used.

Is there a command line tool that looks up the name by the standard way (honouring mDNS and /etc/hosts)?

There is a similar question on Ask DIfferent, but it seems to be specific to OS X.

marked as duplicate by Anthon, jimmij, slm Nov 2 '14 at 12:33

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • You just need any utility that goes through nsswitch, their ping answer there would work for you as well. – Bratchley Aug 16 '14 at 14:24
  • It's true that I can just use ping. But it feels like "overkill" to use ping just to find an IP address. – Kritzefitz Aug 16 '14 at 17:28
6

You can use getent to query various DBs including hosts.

$ getent hosts <hostname>

If your server has a V6 address but you want a V4 address, you may need to use the ahostsv4 DB instead.

$ getent ahostsv4 www.google.com

As an additional tool, you could try calling gethostbyname() in a program. C would be fine, but here is a perl script:

#!/usr/bin/perl
use strict;
use warnings;
use Socket;

my $ip = gethostbyname($ARGV[0]); 
if (defined $ip) {
  my $ip_addr = inet_ntoa($ip);
  print "$ip_addr\n";
}

If a host on the command line has only a single IP, it will be printed below.

  • This isn't really what I'm looking for. This, for example, doesn't work for mDNS. – Kritzefitz Aug 16 '14 at 18:22
  • 2
    @Kritzefitz This is exactly what you're looking for: it's the same resolution code that applications use, based on NSS (unlike hosts, dig and nslookup which are specific to DNS). It should work with mDNS. – Gilles Aug 16 '14 at 19:35
  • Can you clarify what you mean by "doesn't work for mDNS"? You're saying you don't get an address that you would get with "ping"? I'll add in a perl lookup script that should do the same thing to the answer. Try that as well. – BowlOfRed Aug 16 '14 at 19:41
  • @bowlofred gethostbyname() does not produce the same result because it is a backward compatibility interface that only works for IPv4. getaddrinfo() is what you want to use here. – Celada Aug 17 '14 at 2:34
  • Sorry. I've mistaken the use of getent. I looked at it again and it works. Sorry for saying it doesn't work. – Kritzefitz Aug 17 '14 at 12:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.