How to fix "the specified hostname is invalid" error

Endrit Qerreti

Endrit Qerreti

In this tutorial, you will learn how to fix "hostname: the specified hostname is invalid" error.

The error "hostname: the specified hostname is invalid" happens when the hostname that you are trying to set as your machine's hostname, contains invalid characters.

So if you try to use for example, an underscore on your hostname, then you will encounter the error "hostname: the specified hostname is invalid".

Allowed characters for hostname are letters a-z, digits 0-9, you can also use hyphens.

This error can be fixed easily, without having to download or install anything on your machine.

What causes this error?

Before fixing this error, let's see what causes this error, so let's try to replicate it to understand what exactly is the cause of this issue.

Now, as we mentioned the allowed characters that you can use on your hostname, are letters, digits and hyphens.

So if you try to use a hyphen, letter or digit on your hostname, it will work. However, if you want to use let's say an underscore, then you will get the error as shown in the screenshot below.

How to fix this error?

The error "hostname: the specified hostname is invalid" is telling you that the character that you were using to set as hostname, was not a valid character.

an invalid hostname looks like this

ubuntu_22_04

To fix this error, all you have to do remove the invalid character, and use the allowed characters for hostname.

Valid characters that you can use for your hostname, are letters a-z, digits 0-9 and hyphens.

A valid hostname, should look like this

ubuntu2204

or

ubuntu-22-04

Now that you know which are the allowed characters that you can use on your hostname, proceed to set your hostname by using the hostname command.

In this tutorial, we are using Ubuntu 22.04, so to set a hostname on Ubuntu 22.04, you can do so by running the command below

sudo hostname myhostname

To learn more ways of changing the hostname on Ubuntu check out How to change hostname on Ubuntu

Conclusion

In this tutorial, you learned how to fix hostname: the specified hostname is invalid" error. We explained what causes this error by replicating it.

By now you should be able to set a hostname on your machine, without getting this error anymore.