关于127.0.1.1以及是否应该使用/etc/hosts

这种东西都写出来感觉自己是不是太无所事事了orz

起因

一开始只是疑惑为什么debian/ubuntu里面的/etc/hosts有第二行127.0.1.1 <host_name>,查下来才知道127/8的地址都是环路地址,127.0.1.1只是为了确保访问自己的hostname的时候 总是访问的是本机地址。

只是看到一句话比较在意

In the long run the UNIX hostname should not be put in /etc/hosts at all.

是不是说所有的hostname应该交给上级DNS解析(/etc/resolv.conf中指定),而不用自己定义/etc/hosts的意思?

搜索

看到好多地方提到FQDN,就搜了一下,真是纯字面意思…

FQDN(fully qualified domain name)

A fully qualified domain name (FQDN) is the complete domain name for a specific computer, or host, on the Internet. The FQDN consists of two parts: the hostname and the domain name. For example, an FQDN for a hypothetical mail server might be mymail.somecollege.edu. The hostname is mymail, and the host is located within the domain somecollege.edu.

In this example, .edu is the top-level domain (TLD). This is similar to the root directory on a typical workstation, where all other directories (or folders) originate. (Within the .edu TLD, Indiana University Bloomington has been assigned the indiana.edu domain, and has authority to create subdomains within it.)

The same applies to web addresses. For example, www.indiana.edu is the FQDN on the web for IU. In this case, www is the name of the host in the indiana.edu domain.

结论1

不写/etc/hosts的话,FQDN会没法好好显示

The way detection of the fully qualified host name works:

  1. It first gets the hostname, or ‘shortname’. This is the output of uname -n or hostname.
  2. It then gets the IP address for that hostname by consulting /etc/hosts (or whatever you have in /etc/resolv.conf, and falling back to the latter sources if not found in /etc/hosts).
  3. Once it has the IP it then does a reverse lookup by again consulting /etc/hosts.
  4. Once it has a record in /etc/hosts, the first entry is used as the fully qualified hostname.

In a nutshell, if you want fully qualified hostname to work, you should do either:

127.0.0.1 fully.qualified.hostname hostname localhost.localdomain localhost

or

127.0.0.1 localhost.localdomain localhost
1.2.3.4 fully.qualified.hostname hostname

结论2

下面一段引用基本意思就是交给上级DNS处理吧,和没事别删localhost这行

As long as your host agrees with your domain name, specifying it or not in /etc/hosts won’t change anything. Another practice is to have it specified as the domain parameter in /etc/resolv.conf. Not specifying it could simplify your life if, one day, your network administrator changes it. Specifying it doesn’t change anything, as far as I know.

You should definitely leave 127.0.0.1 localhost or 127.0.0.1 localhost localhost.localdomain in /etc/hosts. Some applications could start having a really strange behaviour is localhost binds to anything other than your loopback address because this is a really, really, unexpected setting.

Referece:
Include domain name or not in /etc/hosts?
What is a fully qualified domain name (FQDN)?