Ping localhost error in Linux

We are going to explain how to solve ping localhost error.

You will solve the a similar error like:

ping: unknown host localhost

Solution 1: /etc/hosts

Open the file /etc/hosts with sudo and verify if it has entires for localhost.

Here is how it should looks like the entries for localhost: localhost

::1     localhost ip6-localhost ip6-loopback

Solution 2: /etc/nsswitch.conf

Another cause of the error is bad permissions for the file /etc/nsswitch.conf. The file requires specific permissions: Solve it with the next command:

sudo chmod 644 /etc/nsswitch.conf

Also verify that /etc/nsswitch.conf has the entry:

hosts:      files dns

Solution 3: Disable all firewalls

Trye to temporarily disable iptables, ufw, or any other firewall that may be in place.

Solution 4: Check DNS

Open the file /etc/resolv.conf and validate the DNS specified in the file.


Check Local Loopback interface is up

Execute the command sudo ifconfig it should output:

lo        Link encap:Local Loopback  
          inet addr:  Mask:
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:295 errors:0 dropped:0 overruns:0 frame:0
          TX packets:295 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:43479 (42.4 KiB)  TX bytes:43479 (42.4 KiB)

If no local loopback open the file /etc/network/interfaces (debian/ubuntu) or /etc/sysconfig/network-scripts/ifcfg-lo (red hat/centos). Add the loopback interface and restart networking.

auto lo
iface lo inet loopback

You can also use the command ip link show lo to verify if the loopback interface is up.

1: lo:  mtu 16436 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00