MacOS – Cannot ping localhost

dnsmacos

I have setup a new MacBook Pro retina, things were going well but now I cannot access localhost.

$ ping localhost
ping: cannot resolve localhost: Unknown host

My /etc/hosts file is fine, or at least untouched.

I have tried flushing the DNS cache, and dig localhost spits out

; <<>> DiG 9.8.3-P1 <<>> localhost
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 50562
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;localhost.         IN  A

;; AUTHORITY SECTION:
.           1551    IN  SOA a.root-servers.net. nstld.verisign-grs.com. 2013030800 1800 900 604800 86400

;; Query time: 31 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Fri Mar  8 14:53:09 2013
;; MSG SIZE  rcvd: 102

I am at a loss what to try next!
I have even run OnyX to clean all cache etc…

Best Answer

Maybe your host file got mangled. Open a terminal, and read your hosts file:

vim /private/etc/hosts

This should contain a line that maps localhost to 127.0.0.1:

127.0.0.1   localhost

It could be this file does not exist at all, or the line I gave above is not present. To be able to edit it you need to be superuser, i.e.:

sudo vim /private/etc/hosts

or you can use any other editor besides vim.