17

I would like a command that will resolve a hostname to an IP address, in the same way that a normal program would resolve the hostname. In other words, it has to take into account mDNS (.local) and /etc/hosts, as well as regular DNS. So that rules out host, dig, and nslookup, since all three of those tools only use regular DNS and won't resolve .local addresses.

On Linux, the getent command does exactly what I want. However, getent does not exist on OS X.

Is there a Mac OS X equivalent of getent? I'm aware that I could write one in a few lines using getaddrinfo, and that's what I'll do if I have to, but I was just wondering if there was already a standard command that could do it.

Thanks!

user31708
  • 347
  • 1
  • 3
  • 6

2 Answers2

21

I think dscacheutil is what you're looking for. It supports caching, /etc/hosts, mDNS (for .local).

dscacheutil -q host -a name foo.local

Another option is dns-sd

dns-sd -q foo.local

More information about dnscacheutil.

thrig
  • 34,333
  • 3
  • 63
  • 84
user422009
  • 334
  • 2
  • 2
  • What is a clear example. For example localhost? How to use, what is the output? It does not work. – mathtick Jan 21 '21 at 22:25
  • Another example `dns-sd -G v4v6 raspberrypi-rubelagu.local` that will show the IPv4 and IPv6 addresses of my raspberry pi on my local network (the raspberry was configured with `raspberrypi-rubelagu` as hostname , the default is just `raspberrypi) – RubenLaguna Jun 02 '21 at 08:45
  • 1
    For others looking for a clear example, the "host" and "name" parts are part of the command, not arguments to substitute. Example: `dscacheutil -q host -a name google.com` – Alex Grounds Aug 04 '21 at 19:59
4

(Building on user422009's answer)

Add this to your ~/.bash_profile:

getent() {
  [ "$1" == "hosts" ] && shift
  for x
  do
    echo $x $(dscacheutil -q host -a name $x | awk '/^ip_address/{print $NF}')
  done
}

Then either open a new terminal or source your bash_profile:

. ~/.bash_profile

And then it'll work:

$ getent hosts www.example.com
www.example.com 93.184.216.34
mcknz
  • 103
  • 3
seekoei
  • 41
  • 1
  • 1
    This could end up being _very_ confusing as you're effectively 'shadowing' another command with a Bash function and, if you forget that you shadowed it, you might be confused why `getent` doesn't seem to work as expected on your computer. – Kenny Evitt Oct 04 '21 at 16:23
  • Thanks, if you change "==" to "=" it fixes zsh error "getent:1: = not found" while remaining bash compatible. – jamshid Dec 19 '21 at 07:39