Cannot ping localhost: "unknown host" on Mac OS X El Captain

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.


After living with this for a long time, I figured out (by checking from the Sublime editor) that the issue with my /etc/hosts file was that the "Line Endings" on the file were set to "Mac OS". When I changed the line endings to "Unix", I am able to ping localhost in the terminal and stuff's working as expected.

enter image description here