I left a few things unsaid in my previous post basic hostname set up, and after talking with some people about /etc/hosts, I thought a quick follow up is in order.
Firstly, my preference is to use the ethernet’s ip address to tie the host name to the FQDN, but others like to use 127.0.1.1. There’s a case where you really should use 127.0.1.1 and that’s in laptops where the ethernet interface might disappear when it’s disconnected, probably desktops with dynamic ip addresses, too. But for servers with a static ip address, take your pick, I chose to use eth0.
An example /etc/hosts for a laptop
127.0.0.1 localhost
127.0.1.1 mymailname.com myhostname
Where myhostname is the host name configured in the kernel.
An example /etc/hosts for a server
127.0.0.1 localhost
192.168.1.1 mymailname.com myhostname.mymailname.com someothername myhostname
When the kernel first boots, the host name is configured. How depends on the distribution. Ubuntu seems to use /etc/hostname. In my example /etc/hostname contains myhostname .
When you run the command hostname it does a gethostname() to get the configured host name. It doesn’t reread /etc/hostname every time, it’s stored in the kernel, presumably.
When you want the FQDN, you run hostname -f, it does a gethostname() to get the configured host name, then does a getaddrinfo("myhostname",...) to get the FQDN. Using the last /etc/hosts example, the FQDN is mymailname.com because it’s the first string after the ip address in the line where myhostname appears.
Short names such as the host name myhostname should go at the end of the line, what you want the FQDN to be should be the first string after the ip address, and any other names goes in the middle.
In my examples, I made the FQDN the mail name, because some distributions use the FQDN by default as the mail name. Ubuntu doesn’t, it appears to use /etc/mailname.
Anyway, that’s my understanding based on messing around and reading a man page. Hopefully I’ve explained how the host name and the FQDN is tied together in /etc/hosts.
Related posts: