Format of /etc/hosts on Linux (different from Windows?)

The format of /etc/hosts on Linux and Windows is the same:

IP address        hostname [hostalias]...

where the brackets are the usual way of indicating that something is optional (don't actually type them) and the dots (...) mean there can be more than one.

You shouldn't have to make your host part of a domain. Try it and see. But it would be a good idea to use .localdomain if you don't have a real domain name. It can make host name resolution a little bit quicker due to the ndots option in /etc/resolv.conf.

Note that in this sense, domain means DNS domain (like google.com or stackexchange.com), not a Windows domain or anything like that.

The line starting with ::1 is for IPv6. ::1 is like 127.0.0.1 under the new addressing scheme. Run ifconfig lo and you should see it has two addresses. Note the entry starting with inet6.

$ ifconfig lo
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
...

See the hosts(5) man page for more details.


You always want the 127.0.0.1 address to resolve first to localhost. If there is a domain you can use that too, but then make sure localhost is listed second. If you want to add aliases for your machine that will lookup to the loopback address you can keep adding them as space separated values on that line. Specifying a domain here is optional, but don't remove "localhost" from the options.


I cannot speak to how Windows may differ from Linux, but the format of the local machine's definition affects the results you will obtain from the 'hostname' command.

The format I find works most consistently well is this:

127.0.0.1 etest.mydomain.com etest localhost

The important thing I have found is to have the FQDN first and the aliases, in any order, after it.

If you experiment with re-arranging the names after the IP address and then using the 'hostname -s' (short name) and 'hostname -f' (fully-qualified domain name or FQDN) commands you will see what I mean. It should look something like this:

$ hostname -s
etest

$ hostname -f
etest.mydomain.com

'hostname' by itself should return whatever name you entered for the host in /etc/conf.d/hostname or /etc/hostname (location of the file varies by distribution, but should be found under /etc somewhere).

If you change the order of the names you may find that "hostname -f" gives you responses like "localhost" or "hostname: system error". The only arrangement I have found that works correctly is putting the FQDN first.

I always set the IPv6 local address line (::1) the same way, i.e.:

::1 etest.mydomain.com etest localhost

I know some distributions set the IPv6 name to something like ip6-localhost. I don't really use IPv6 yet, so can't comment on what the best settings for this line would be. I can just say that in an IPv4 network it works to have both lines with the same names.

Tags:

Linux

Hosts