While installing a Linux distro on the system, users are asked to set a hostname, which is also the computer’s name. If the users want to change it, the file “/etc/hostname” is edited, and then the system is restarted for the changes to take effect.
The problem is that you may encounter the error “Hostname: Name or Service not known” while trying to use a command with sudo privileges.
Today’s writing illustrates the error when the hostname is changed on a system.
- Reason for the “Hostname: Name or Service not known” Error
- Solution 1: Add Hostname in the /etc/hosts Configuration File (Permanent)
- Solution 2: Set a Temporary Hostname on Linux
Reason for the “Hostname: Name or Service not known” Error
Linux users faced this error when they changed the hostname on their system. The hostname is usually set during the installation process of the system. Still, most users set it as default, and later they need to change it, which could cause the error “Hostname: Name or Service not known.”
The file “/etc/host” maps hostnames to IP addresses, and any differences there pop up the error, which can only be fixed by matching and changing the hostname in the same file.
Solution 1: Add Hostname in the /etc/hosts Configuration File (Permanent)
First, execute this command to view the hostname on your system to fix this annoying error when using a command with sudo privileges:
In this case, the hostname on the system is “ubuntu,” which may be different on your system.
Now that you have viewed your system’s hostname let’s match it with “/etc/hosts” and see if it stands out:
$ cat /etc/hosts
As seen above, the line after “127.0.0.1 localhost” is empty, which means the system couldn’t find any hostname, causing the error. This is the root cause of the problem and is fixed by adding a hostname:
Let’s add “127.0.0.1” as the IP address and “itslinuxfoss” as the hostname:
Save the file using “CTRL + X” and then type “Y.” Now execute this command to confirm the changes:
$ cat /etc/hosts
A new entity has now appeared and should fix all the problems related to the hostname error.
Solution 2: Set a Temporary Hostname on Linux
To set a temporary hostname on Linux requires sudo privileges and involves the execution of this command:
$ sudo hostname <New-Host-Name>
Let’s change the hostname to “ubuntu” using this command:
$ sudo hostname ubuntu
The above command is successfully executed. Still, it will take effect immediately, so use the “bash” command for the changes to take effect:
The difference has now taken effect, and the hostname is temporarily changed to “ubuntu” from “itslinuxfoss.”
You get the error “Hostname: Name or Service not Known” due to an unresolved host error which prevents the user from executing a command with sudo privileges. As explained, a simple mistake in the file “/etc/hosts” is the cause and can be resolved by providing the correct credentials.
This guide has explained why the user faced this error and two ways to fix it.