MacOS – Cannot ping localhost: “unknown host” on Mac OS X El Captain

apachednsmacosNetwork

I am trying to resolve localhost which right now is "not found"

if I ping localhost – I am getting

ping: cannot resolve localhost: Unknown host

I have made sure that the /etc/hosts file has the below entries that are necessary to have the resolution for localhost –

127.0.0.1   localhost
255.255.255.255 broadcasthost
::1             localhost

However, when I ping 127.0.0.1 it is successful –

PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.052 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.066 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.054 ms
^C
--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.052/0.057/0.066/0.006 ms

In doubts of this getting blocked by my antivirus – I have also disabled my "web root secure anywhere" anti-virus… and it did not solve anything.

Also, I have noticed that when I restarted my machine – for the first few mins the ping localhost worked and stopped working after few mins. not sure how to track what stopped it from working.

Based on the answer at DNS not resolving on Mac OS X – tried "dig @8.8.8.8 localhost" only to find that there was no "answer" section at all.

localhost:~ $ dig @8.8.8.8 localhost

; <<>> DiG 9.8.3-P1 <<>> @8.8.8.8 localhost
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 3535
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 0

;; QUESTION SECTION:
;localhost.         IN  A

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

;; Query time: 20 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu Aug 18 17:15:07 2016
;; MSG SIZE  rcvd: 102

As requested, the output for "ls -le@ /etc/hosts" –

$ ls -le@ /etc/hosts
-rw-r--r--  1 root  wheel  6126 Aug 18 17:09 /etc/hosts

Best Answer

I have solved the problem by restoring my Hosts file (it was empty):

But before, you have to check your hosts file.

cat /etc/hosts

If nothing is shown, that means your hosts file is empty.

Then just copy and paste this over the existing hosts file then save it as plain text to restore it.

##
# Host Database
#
# localhost is used to configure the loopback interface 
# when the system is booting. Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost

If your hosts file is not empty, your can try to delete it and add it again with this lines.