8.3. Setting the Hostname and Configuring the Name Service

The purpose of assigning names to IP numbers is to make them easier for people to remember. In reality, an IP address identifies a network interface associated with a device such as a network card. Since each machine can have several network cards, and several interfaces on each card, one single computer can have several names in the domain name system.

Each machine is, however, identified by a main (or “canonical”) name, stored in the /etc/hostname file and communicated to the Linux kernel by initialization scripts through the hostname command. The current value is available in a virtual filesystem, and you can get it with the cat /proc/sys/kernel/hostname command.

BACK TO BASICS /proc/ and /sys/, virtual filesystems

The /proc/ and /sys/ file trees are generated by “virtual” filesystems. This is a practical means of recovering information from the kernel (by listing virtual files) and communicating them to it (by writing to virtual files).

/sys/ in particular is designed to provide access to internal kernel objects, especially those representing the various devices in the system. The kernel can, thus, share various pieces of information: the status of each device (for example, if it is in energy saving mode), whether it is a removable device, etc. Note that /sys/ has only existed since kernel version 2.6.

Surprisingly, the domain name is not managed in the same way, but comes from the complete name of the machine, acquired through name resolution. You can change it in the /etc/hosts file; simply write a complete name for the machine there at the beginning of the list of names associated with the address of the machine, as in the following example:

  1. 127.0.0.1 localhost
  2. 192.168.0.1 arrakis.falcot.com arrakis

8.3.1. 名称解析

Linux 的名称解析机制是模块化的且可使用 /etc/nsswitch.conf 宣称的数据源。涉及主机名称解析的条目是 hosts。缺省,它包括 files dns,表示系统先参照 /etc/hosts 文件,再参照 DNS 服务器。NIS/NIS+ 或 LDAP 服务器是另个来源选择。

说明 NSS 与 DNS

专门用于查找 DNS 的命令(特别是 host),未使用标准的名称解析机制 (NSS)。也就是,完全未考虑 /etc/nsswitch.conf,也不使用 /etc/hosts

8.3.1.1. 配置 DNS 服务器

DNS (网域名称服务) 是映射名称至 IP 地址的分布式阶层服务,同时也反向映射。尤其是,把人可阅读的名称,如 www.eyrolles.com 映射至实际的 IP 地址 213.244.11.247

必须先设置 DNS 服务器,才能用到 DNS 信息。Falcot 公司自设该服务器,但个人用户可能使用 ISP 提供的 DNS 服务器。

DNS 服务器的用法在 /etc/resolv.conf 内,每个一列,在 IP 地址前有 nameserver 键词,如下:

  1. nameserver 212.27.32.176
  2. nameserver 212.27.32.177
  3. nameserver 8.8.8.8

网络由 NetworkManager 管理或经由 DHCP 配置时,可以自动处理 (与覆写) /etc/resolv.conf 文件。

8.3.1.2. /etc/hosts 文件

地区网络没有名称服务器时,仍可以在保留给地区网络的 /etc/hosts 文件内,创建 IP 地址与主机名称的小型对照表。此文件的语法极简单:每列一个固定 IP 地址,然后是相关的名称 (第一个是 “完全合格”,表示包括网域名称)。

即使网络停摆或 DNS 服务器不通仍可近用此文件,但只适用于本地区网络所有机器重制的内容。即使是极微小的变动,都需要更新各地所有的文件。所以, /etc/hosts 通常只包括最重要的条目。

这个文件对未连上互联网的小型网络是够用的,5 部以内的机器,建议安装一个 DNS 服务器较佳。

秘诀 绕过 DNS

某些应用程序先检查 /etc/hosts 文件才查找 DNS,与 DNS 送回数据不同的部分,可以先保存在这里,并略过 DNS 的名称解析。

修改 DNS 但尚未布署前,这种做法可以测试网站名称与 IP 地址的对应性。

另一个可能用法是把流量转移至指定的区域主机,避免大流量进入指定的主机。例如,可以绕过专供广告使用的服务器主机名称,让结果更顺畅、少些干扰。