Why is my hostname resolution taking so long?

I was able to fix this issue by explicitly setting the HostName using scutil to be the same value as LocalHostName:

$ scutil --set HostName $(scutil --get LocalHostName)

Now:

$ sudo scutil --set HostName MacBook-Pro
$ time python -c 'import socket; print(socket.getfqdn())'
MacBook-Pro
python -c 'import socket; print(socket.getfqdn())'  0.01s user 0.00s system 86% cpu 0.016 total

I was confused before because of the following:

$ scutil --get LocalHostName
MacBook-Pro

$ hostname
MacBook-Pro.local

But:

$ scutil --get HostName
HostName: not set

I originally had the same issue, but eventually resolved it.

I used to have:

$ scutil --get HostName
Michaels-Macbook-Pro
$ scutil --get LocalHostName
Michaels-Macbook-Pro
$ time python -c 'import socket; socket.getfqdn()'
... 30s ...

Then I changed:

$ scutil --set HostName Michaels-Macbook-Pro.local
$ time python -c 'import socket; socket.getfqdn()'
... 5s ...

Then I added into: /etc/hosts

127.0.0.1       localhost Michaels-Macbook-Pro.local
::1             localhost Michaels-Macbook-Pro.local

It became fast.


Had the same issue, but your suggestions didn't work for me.

Eventually, I fixed it by doing this once I did this:

sudo scutil --set HostName uranus.local

My machine host is 'uranus'. I only had to add '.local' to it.