20

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!

2 Answers 2

23

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.

3
  • What is a clear example. For example localhost? How to use, what is the output? It does not work.
    – safetyduck
    Commented Jan 21, 2021 at 22:25
  • 1
    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) Commented Jun 2, 2021 at 8: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 Commented Aug 4, 2021 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
2
  • 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. Commented Oct 4, 2021 at 16:23
  • Thanks, if you change "==" to "=" it fixes zsh error "getent:1: = not found" while remaining bash compatible.
    – jamshid
    Commented Dec 19, 2021 at 7:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .