Chapter 9. Understanding your Network and its Configuration(第 9 章 了解网络及其配置)

Networking is the practice of connecting computers and sending data between them. That sounds simple enough, but to understand how it works, you need to ask two fundamental questions:

网络是连接计算机并在它们之间传递数据的实践。

听起来很简单,但要理解它的工作原理,你需要提出两个基本问题:

o How does the computer sending the data know where to send its data?
o When the destination computer receives the data, how does it know what it just received?

  • 发送数据的计算机如何知道要将数据发送到哪里?
  • 目标计算机接收到数据后,如何知道它刚刚接收到了什么?

A computer answers these questions by using a series of components, with each one responsible for a certain aspect of sending, receiving, and identifying data. The components are arranged in groups that form network layers, which stack on top of each other in order to form a complete system. The Linux kernel handles networking in a similar way to the SCSI subsystem described in Chapter 3.

计算机通过使用一系列组件来回答这些问题,每个组件负责发送、接收和识别数据的某个方面。

这些组件按照层次分组,堆叠在一起形成一个完整的系统。

Linux内核处理网络的方式与第三章中描述的SCSI子系统类似。

Because each layer tends to be independent, it’s possible to build networks with many different combinations of components. This is where network configuration can become very complicated. For this reason, we’ll begin this chapter by looking at the layers in very simple networks. You’ll learn how to view your own network settings, and when you understand the basic workings of each layer, you’ll be ready to learn how to configure those layers by yourself. Finally, you’ll move on to more advanced topics like building your own networks and configuring firewalls. (Skip over that material if your eyes start to glaze over; you can always come back.)

由于每个层次往往是独立的,可以使用许多不同组合的组件构建网络。

这就是网络配置可能变得非常复杂的地方。

因此,我们将从非常简单的网络中的层次开始本章的学习。

你将学习如何查看自己的网络设置,当你理解每个层次的基本工作原理时,你将准备好自己配置这些层次。

最后,你将进一步学习如何构建自己的网络和配置防火墙等高级主题。

45(如果你对此感到困惑,可以跳过这部分内容,随时回来阅读。)

9.1 Network Basics(网络基础)

Before getting into the theory of network layers, take a look at the simple network shown in Figure 9-1.

在了解网络层理论之前,请先看一下图 9-1 所示的简单网络。

Figure 9-1. A typical local area network with a router that provides Internet access

Figure 9-1. A typical local area network with a router that provides Internet access

图9-1. 具有提供互联网访问的路由器的典型局域网

This type of network is ubiquitous; most home and small office networks are configured this way. Each machine connected to the network is called a host. The hosts are connected to a router, which is a host that can move data from one network to another. These machines (here, Hosts A, B, and C) and the router form a local area network (LAN). The connections on the LAN can be wired or wireless.

这种类型的网络无处不在,大多数家庭和小型办公室网络都是这样配置的。

连接到网络的每台机器都被称为主机。

主机连接到一台路由器上,路由器是一台可以将数据从一个网络传输到另一个网络的主机。

这些机器(这里是主机A、B和C)以及路由器组成了一个局域网(LAN)。

局域网上的连接可以是有线的或无线的。

The router is also connected to the Internet—the cloud in the figure. Because the router is connected to both the LAN and the Internet, all machines on the LAN also have access to the Internet through the router. One of the goals of this chapter is to see how the router provides this access.

路由器还连接到互联网-图中的云。

由于路由器连接到局域网和互联网,局域网上的所有机器也可以通过路由器访问互联网。

本章的目标之一是了解路由器如何提供这种访问。

Your initial point of view will be from a Linux-based machine such as Host A on the LAN in Figure 9-1.

您的初始视角将来自于图9-1中局域网上的基于Linux的机器,例如主机A。

9.1.1 Packets(数据包)

A computer transmits data over a network in small chunks called packets, which consist of two parts: a header and a payload. The header contains identifying information such as the origin/destination hosts and basic protocol. The payload, on the other hand, is the actual application data that the computer wants to send (for example, HTML or image data).

计算机通过网络以小块称为数据包的形式传输数据,数据包由两部分组成:头部和有效载荷。

头部包含识别信息,例如源/目标主机和基本协议。

而有效载荷则是计算机要发送的实际应用数据(例如HTML或图像数据)。

Packets allow a host to communicate with others “simultaneously,” because hosts can send, receive, and process packets in any order, regardless of where they came from or where they’re going. Breaking messages into smaller units also makes it easier to detect and compensate for errors in transmission

数据包使主机能够与其他主机“同时”进行通信,因为主机可以以任何顺序发送、接收和处理数据包,而不考虑它们来自哪里或要去哪里。

将消息分成较小的单元也使得更容易检测和补偿传输中的错误。

For the most part, you don’t have to worry about translating between packets and the data that your application uses, because the operating system has facilities that do this for you. However, it is helpful to know the role of packets in the network layers that you’re about to see

在大多数情况下,您不必担心在数据包和应用程序使用的数据之间进行转换,因为操作系统有相应的功能来完成这一任务。

然而,了解数据包在即将介绍的网络层中的作用是很有帮助的。

9.2 Network Layers(网络层)

A fully functioning network includes a full set of network layers called a network stack. Any functional network has a stack. The typical Internet stack, from the top to bottom layer, looks like this:

一个完全运作的网络包括一个称为网络堆栈的完整的网络层集合。

任何功能性网络都有一个堆栈。典型的互联网堆栈,从顶层到底层,如下所示:

o Application layer. Contains the “language” that applications and servers use to communicate; usually a high-level protocol of some sort. Common application layer protocols include Hypertext Transfer Protocol (HTTP, used for the Web), Secure Socket Layer (SSL), and File Transfer Protocol (FTP). Application layer protocols can often be combined. For example, SSL is commonly used in conjunction with HTTP.

o 应用层。包含应用程序和服务器用于通信的“语言”;通常是一种高级协议。

常见的应用层协议包括超文本传输协议(HTTP,用于Web)、安全套接字层(SSL)和文件传输协议(FTP)。

应用层协议通常可以结合使用。

例如,SSL常与HTTP一起使用。

o Transport layer. Defines the data transmission characteristics of the application layer. This layer includes data integrity checking, source and destination ports, and specifications for breaking application data into packets (if the application layer has not already done so). Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) are the most common transport layer protocols. The transport layer is also sometimes called the protocol layer.

o 传输层。定义应用层的数据传输特性。该层包括数据完整性检查、源端口和目标端口,以及将应用数据分解为数据包的规范(如果应用层尚未这样做)。

传输控制协议(TCP)和用户数据报协议(UDP)是最常见的传输层协议。传输层有时也称为协议层。

o Network or Internet layer. Defines how to move packets from a source host to a destination host. The particular packet transit rule set for the Internet is known as Internet Protocol (IP). Because we’ll only talk about Internet networks in this book, we’ll really only be talking about the Internet layer. However, because network layers are meant to be hardware independent, you can simultaneously configure several independent network layers (such as IP, IPv6, IPX, and AppleTalk) on a single host.

o 网络或互联网层。定义如何将数据包从源主机移动到目标主机。

互联网的特定数据包传输规则集被称为互联网协议(IP)。

因为本书只讨论互联网网络,所以我们只会讨论互联网层。

然而,由于网络层旨在与硬件无关,您可以在单个主机上同时配置几个独立的网络层(例如IP、IPv6、IPX和AppleTalk)。

o Physical layer. Defines how to send raw data across a physical medium, such as Ethernet or a modem. This is sometimes called the link layer or host-to-network layer.

o 物理层。定义如何通过物理介质发送原始数据,例如以太网或调制解调器。

有时也称为链路层或主机到网络层。

It’s important to understand the structure of a network stack because your data must travel through these layers at least twice before it reaches a program at its destination. For example, if you’re sending data from Host A to Host B, as shown in Figure 9-1, your bytes leave the application layer on Host A and travel through the transport and network layers on Host A; then they go down to the physical medium, across the medium, and up again through the various lower levels to the application layer on Host B in much the same way. If you’re sending something to a host on the Internet through the router, it will go through some (but usually not all) of the layers on the router and anything else in between.

了解网络堆栈的结构很重要,因为您的数据在到达目的地的程序之前必须经过这些层至少两次。

例如,如果您要从主机A发送数据到主机B,如图9-1所示,您的字节将离开主机A的应用层,并通过主机A的传输和网络层传输;

然后它们经过物理介质,横跨介质,再通过各个较低层次上升到主机B的应用层。

如果您通过路由器向互联网上的主机发送数据,它将通过路由器上的一些层(但通常不是全部)以及中间的其他任何设备。

The layers sometimes bleed into each other in strange ways because it can be inefficient to process all of them in order. For example, devices that historically dealt with only the physical layer now sometimes look at the transport and Internet layer data to filter and route data quickly. (Don’t worry about this when you’re learning the basics.)

由于按顺序处理所有层可能效率低下,层之间有时会相互交叉。

例如,过去只处理物理层的设备现在有时会查看传输和互联网层的数据,以便快速过滤和路由数据。(在学习基础知识时不必担心这个问题。)

We’ll begin by looking at how your Linux machine connects to the network in order to answer the where question at the beginning of the chapter. This is the lower part of the stack—the physical and network layers. Later, we’ll look at the upper two layers that answer the what question.

我们将从查看Linux机器连接到网络的方式开始,以回答本章开头的“在哪里”问题。

这是堆栈的较低部分-物理层和网络层。

稍后,我们将查看回答“是什么”问题的上两层。

NOTE You might have heard of another set of layers known as the Open Systems Interconnection (OSI) Reference Model. This is a seven-layer network model often used in teaching and designing networks, but we won’t cover the OSI model because you’ll be working directly with the four layers described here. To learn a lot more about layers (and networks in general), see Andrew S. Tanenbaum and David J. Wetherall’s Computer Networks, 5th edition (Prentice Hall, 2010).

注意:你可能听说过另一组称为开放系统互连(OSI)参考模型的层次结构。这是一个通常用于教学和设计网络的七层网络模型,但我们不会涉及OSI模型,因为您将直接使用这里描述的四层。

要了解更多关于层次结构(以及网络的一般知识),

请参阅Andrew S. Tanenbaum和David J. Wetherall的《计算机网络》第5版(Prentice Hall,2010)。

9.3 The Internet Layer(互联网层)

Rather than start at the very bottom of the network stack with the physical layer, we’ll start at the network layer because it can be easier to understand. The Internet as we currently know it is based on the Internet Protocol, version 4 (IPv4), though version 6 (IPv6) is gaining adoption. One of the most important aspects of the Internet layer is that it’s meant to be a software network that places no particular requirements on hardware or operating systems. The idea is that you can send and receive Internet packets over any kind of hardware, using any operating system.

与其从网络堆栈的物理层开始,我们将从网络层开始,因为它更容易理解。

我们目前所知的互联网是基于互联网协议第4版(IPv4)的,虽然第6版(IPv6)正在得到采用。

互联网层最重要的一个方面是它是一个软件网络,对硬件或操作系统没有特定要求。

理念是你可以使用任何类型的硬件和任何操作系统来发送和接收互联网数据包。

The Internet’s topology is decentralized; it’s made up of smaller networks called subnets. The idea is that all subnets are interconnected in some way. For example, in Figure 9-1, the LAN is normally a single subnet.

互联网的拓扑结构是分散的,由称为子网的较小网络组成。理念是所有子网以某种方式相互连接。例如,在图9-1中,局域网通常是一个单一的子网。

A host can be attached to more than one subnet. As you saw in 9.1 Network Basics, that kind of host is called a router if it can transmit data from one subnet to another (another term for router is gateway). Figure 9-2 refines Figure 9-1 by identifying the LAN as a subnet, as well as Internet addresses for each host and the router. The router in the figure has two addresses, the local subnet 10.23.2.1 and the link to the Internet (but this Internet link’s address is not important right now so it’s just marked “Uplink Address”). We’ll look first at the addresses and then the subnet notation.

一个主机可以连接到多个子网。

正如你在9.1网络基础中看到的那样,如果一个主机可以从一个子网传输数据到另一个子网,那么它被称为路由器(另一个术语是网关)。

图9-2通过为每个主机和路由器标识局域网和互联网地址,进一步完善了图9-1。

图中的路由器有两个地址,本地子网10.23.2.1和与互联网的链接(但是这个互联网链接的地址现在并不重要,所以只标记为“上行链路地址”)。

我们首先看地址,然后再看子网表示法。

Each Internet host has at least one numeric IP address in the form of a.b.c.d, such as 10.23.2.37. An address in this notation is called a dotted-quad sequence. If a host is connected to multiple subnets, it has at least one IP address per subnet. Each host’s IP address should be unique across the entire Internet, but as you’ll see later, private networks and NAT can make this a little confusing.

每个互联网主机至少有一个数字IP地址,形式为a.b.c.d,例如10.23.2.37。这种表示法的地址称为点分十进制序列。

如果一个主机连接到多个子网,它每个子网至少有一个IP地址。

每个主机的IP地址在整个互联网上应该是唯一的,但是正如你稍后会看到的,私有网络和NAT可能会让这有点混乱。

Figure 9-2. Network with IP addresses

Figure 9-2. Network with IP addresses

图9-2. 带有IP地址的网络

Technically, an IP address consists of 4 bytes (or 32 bits), abcd. Bytes a and d are numbers from 1 to 254, and b and c are numbers from 0 to 255. A computer processes IP addresses as raw bytes. However, it’s much easier for a human to read and write a dotted-quad address, such as 10.23.2.37, instead of something ugly like the hexadecimal 0x0A170225.

从技术上讲,IP地址由4个字节(或32位)组成,即abcd。字节a和d是从1到254的数字,而b和c是从0到255的数字。

计算机以原始字节形式处理IP地址。

然而,对于人类来说,读写点分十进制地址(如10.23.2.37)比读写十六进制地址0x0A170225要容易得多。

IP addresses are like postal addresses in some ways. To communicate with another host, your machine must know that other host’s IP address. Let’s take a look at the address on your machine.

IP地址在某些方面类似于邮政地址。

为了与另一个主机通信,您的计算机必须知道该主机的IP地址。让我们来看看您计算机上的地址。

9.3.1 Viewing Your Computer’s IP Addresses(查看您计算机的IP地址)

One host can have many IP addresses. To see the addresses that are active on your Linux machine, run

一台主机可以有多个 IP 地址。要查看 Linux 机器上的活动地址,请运行

$ ifconfig

There will probably be a lot of output, but it should include something like this:

可能会有很多输出,但应该包括类似这样的内容:

eth0 Link encap:Ethernet HWaddr 10:78:d2:eb:76:97
 inet addr:10.23.2.4 Bcast:10.23.2.255 Mask:255.255.255.0
 inet6 addr: fe80::1278:d2ff:feeb:7697/64 Scope:Link
 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
 RX packets:85076006 errors:0 dropped:0 overruns:0 frame:0
 TX packets:68347795 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:86427623613 (86.4 GB) TX bytes:23437688605 (23.4 GB)
 Interrupt:20 Memory:fe500000-fe520000

The ifconfig command’s output includes many details from both the Internet layer and the physical layer. (Sometimes it doesn’t even include an Internet address at all!) We’ll discuss the output in more detail later, but for now, concentrate on the second line, which reports that the host is configured to have an IPv4 address (inet addr) of 10.23.2.4. On the same line, a Mask is reported as being 255.255.255.0. This is a subnet mask, which defines the subnet that an IP address belongs to. Let’s see how that works

ifconfig命令的输出包含了来自互联网层和物理层的许多细节。

(有时它甚至不包含任何互联网地址!)我们稍后会详细讨论输出内容,但现在请专注于第二行,该行报告了主机配置的IPv4地址(inet addr)为10.23.2.4。

在同一行上,掩码被报告为255.255.255.0。

这是一个子网掩码,用于定义IP地址所属的子网。

让我们看看它是如何工作的。

NOTE The ifconfig command, as well some of the others you’ll see later in this chapter (such as route and arp), has been technically supplanted with the newer ip command. The ip command can do more than the old commands, and it is preferable when writing scripts. However, most people still use the old commands when manually working with the network, and these commands can also be used on other versions of Unix. For this reason, we’ll use the old-style commands.

注意

ifconfig命令以及本章后面将要介绍的其他一些命令(如route和arp),在技术上已经被更新的ip命令所取代。

ip命令可以执行比旧命令更多的功能,并且在编写脚本时更可取。

然而,大多数人在手动处理网络时仍然使用旧命令,并且这些命令也可以在其他版本的Unix上使用。因此,我们将使用旧式命令。

9.3.2 Subnets(子网网络)

A subnet is a connected group of hosts with IP addresses in some sort of order. Usually, the hosts are on the same physical network, as shown in Figure 9-2. For example, the hosts between 10.23.2.1 and 10.23.2.254 could comprise a subnet, as could all hosts between 10.23.1.1 and 10.23.255.254.

子网是一组具有按某种顺序排列的IP地址的主机的连接。

通常,这些主机位于同一物理网络上,如图9-2所示。

例如,位于10.23.2.1和10.23.2.254之间的主机可以构成一个子网,位于10.23.1.1和10.23.255.254之间的所有主机也可以构成一个子网。

You define a subnet with two pieces: a network prefix and a subnet mask (such as the one in the output of ifconfig in the previous section). Let’s say you want to create a subnet containing the IP addresses between 10.23.2.1 and 10.23.2.254. The network prefix is the part that is common to all addresses in the subnet; in this example, it’s 10.23.2.0, and the subnet mask is 255.255.255.0. Let’s see why those are the right numbers. It’s not immediately clear how the prefix and mask work together to give you all possible IP addresses on a subnet. Looking at the numbers in binary form helps clear it up. The mask marks the bit locations in an IP address that are common to the subnet. For example, here are the binary forms of 10.23.2.0 and 255.255.255.0:

您可以使用两个部分来定义一个子网:网络前缀和子网掩码(例如在上一节的ifconfig输出中)。

假设您想创建一个包含10.23.2.1和10.23.2.254之间IP地址的子网。

网络前缀是在子网中所有地址中都相同的部分;在这个例子中,它是10.23.2.0,子网掩码是255.255.255.0。

让我们看看为什么这些是正确的数字。如何将前缀和掩码结合在一起以获得子网上的所有可能的IP地址并不立即清楚。

以二进制形式查看数字可以帮助理解。掩码标记了在IP地址中与子网相同的位位置。

例如,这是10.23.2.0和255.255.255.0的二进制形式:

Now, let’s use boldface to mark the bit locations in 10.23.2.0 that are 1s in 255.255.255.0:

现在,让我们使用粗体来标记10.23.2.0中与255.255.255.0中的1相对应的位位置:

10.23.2.0: 00001010 00010111 00000010 00000000

Look at the bits that are not in bold. You can set any number of these bits to 1 to get a valid IP address in this subnet, with the exception of all 0s or all 1s.

Putting it all together, you can see how a host with an IP address of 10.23.2.1 and a subnet mask of 255.255.255.0 is on the same subnet as any other computers that have IP addresses beginning with 10.23.2. You can denote this entire subnet as 10.23.2.0/255.255.255.0.

看一下那些没有加粗的位。你可以将其中任意数量的位设置为1,以获得该子网中的一个有效IP地址,除非全为0或全为1。

把所有这些放在一起,你可以看到一个具有IP地址为10.23.2.1和子网掩码为255.255.255.0的主机与具有以10.23.2开头的任何其他计算机在同一个子网上。

你可以将整个子网表示为10.23.2.0/255.255.255.0。

9.3.3 Common Subnet Masks and CIDR Notation(常见的子网掩码和CIDR表示法)

If you’re lucky, you’ll only deal with easy subnet masks like 255.255.255.0 or 255.255.0.0, but you may be unfortunate and encounter stuff like 255.255.255.192, where it isn’t quite so simple to determine the set of addresses that belong to the subnet. Furthermore, it’s likely that you’ll also encounter a different form of subnet representation called Classless Inter-Domain Routing (CIDR) notation, where a subnet such as 10.23.2.0/255.255.255.0 is written as 10.23.2.0/24.

如果你很幸运,你可能只需处理像255.255.255.0或255.255.0.0这样简单的子网掩码,但你可能不那么幸运,会遇到像255.255.255.192这样的复杂情况,这时确定属于子网的地址集就不那么简单了。

此外,你可能也会遇到另一种子网表示形式,称为无类别域间路由(CIDR)表示法,其中一个子网如10.23.2.0/255.255.255.0会被写成10.23.2.0/24。

To understand what this means, look at the mask in binary form (as in the example you saw in the preceding section). You’ll find that nearly all subnet masks are just a bunch of 1s followed by a bunch of 0s. For example, you just saw that 255.255.255.0 in binary form is 24 1-bits followed by 8 0-bits. The CIDR notation identifies the subnet mask by the number of leading 1s in the subnet mask. Therefore, a combination such as 10.23.2.0/24 includes both the subnet prefix and its subnet mask.

要理解这意味着什么,看一下掩码的二进制形式(就像你在前面部分看到的示例)。

你会发现几乎所有的子网掩码都是一串1后面跟着一串0。

例如,你刚才看到255.255.255.0的二进制形式是24个1位后跟着8个0位。

CIDR表示法通过子网掩码中前导1的数量来标识子网掩码。

因此,一个类似于10.23.2.0/24的组合包括子网前缀及其子网掩码。

Table 9-1 shows several example subnet masks and their CIDR forms.

Table 9-1. Subnet Masks

Table 9-1. Subnet Masks

表9-1. 子网掩码

NOTE If you aren’t familiar with conversion between decimal, binary, and hexadecimal formats, you can use a calculator utility such as bc or dc to convert between different radix representations. For example, in bc, you can run the command obase=2; 240 to print the number 240 in binary (base 2) form.

注意:如果您不熟悉十进制、二进制和十六进制格式之间的转换,您可以使用诸如bc或dc之类的计算器实用程序在不同的基数表示之间进行转换。

例如,在bc中,您可以运行命令obase=2; 240以打印数字240的二进制(基数2)形式。

Identifying subnets and their hosts is the first building block to understanding how the Internet works. However, you still need to connect the subnets

识别子网及其主机是理解互联网运作方式的第一步。

然而,您仍然需要连接这些子网。

9.4 Routes and the Kernel Routing Table(路由和内核路由表)

Connecting Internet subnets is mostly a process of identifying the hosts connected to more than one subnet. Returning to Figure 9-2, think about Host A at IP address 10.23.2.4. This host is connected to a local network of 10.23.2.0/24 and can directly reach hosts on that network. To reach hosts on the rest of the Internet, it must communicate through the router at 10.23.2.1.

连接互联网子网主要是识别连接到多个子网的主机的过程。回顾图9-2,考虑一下IP地址为10.23.2.4的主机A。

该主机连接到一个本地网络10.23.2.0/24,并且可以直接访问该网络上的主机。

要访问互联网上的其他主机,它必须通过位于10.23.2.1的路由器进行通信。

How does the Linux kernel distinguish between these two different kinds of destinations? It uses a destination configuration called a routing table to determine its routing behavior. To show the routing table, use the route -n command. Here’s what you might see for a simple host such as 10.23.2.4:

Linux内核如何区分这两种不同的目的地?

它使用称为路由表的目标配置来确定其路由行为。

要显示路由表,请使用route -n命令。以下是一个简单主机(例如10.23.2.4)可能看到的内容:

$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.23.2.1 0.0.0.0 UG 0 0 0 eth0
10.23.2.0 0.0.0.0 255.255.255.0 U 1 0 0 eth0

The last two lines here contain the routing information. The Destination column tells you a network prefix, and the Genmask column is the netmask corresponding to that network. There are two networks defined in this output: 0.0.0.0/0 (which matches every address on the Internet) and 10.23.2.0/24. Each network has a U under its Flags column, indicating that the route is active (“up”).

这里的最后两行包含了路由信息。目的地列告诉您一个网络前缀,而Genmask列是与该网络对应的网络掩码。

在此输出中定义了两个网络:0.0.0.0/0(与互联网上的每个地址匹配)和10.23.2.0/24。

每个网络在其标志列下都有一个U,表示该路由是活动的(“up”)。

Where the destinations differ is in the combination of their Gateway and Flags columns. For 0.0.0.0/0, there is a G in the Flags column, meaning that communication for this network must be sent through the gateway in the Gateway column (10.23.2.1, in this case). However, for 10.23.2.0/24, there is no G in Flags, indicating that the network is directly connected in some way. Here, 0.0.0.0 is used as a stand-in under Gateway. Ignore the other columns of output for now

目的地之间的区别在于它们的网关和标志列的组合。

对于0.0.0.0/0,在标志列中有一个G,表示该网络的通信必须通过网关列中的网关发送(在本例中为10.23.2.1)。

然而,对于10.23.2.0/24,在标志中没有G,表示该网络以某种方式直接连接。

在这里,0.0.0.0被用作网关的替代。暂时忽略其他输出列。

There’s one tricky detail: Say the host wants to send something to 10.23.2.132, which matches both rules in the routing table, 0.0.0.0/0 and 10.23.2.0/24. How does the kernel know to use the second one? It chooses the longest destination prefix that matches. This is where CIDR network form comes in particularly handy: 10.23.2.0/24 matches, and its prefix is 24 bits long; 0.0.0.0/0 also matches, but its prefix is 0 bits long (that is, it has no prefix), so the rule for 10.23.2.0/24 takes priority.

有一个棘手的细节:假设主机想要发送一些东西到10.23.2.132,在路由表中同时匹配两个规则,0.0.0.0/0和10.23.2.0/24。

内核如何知道要使用第二个规则?它选择最长的目标前缀进行匹配。

这就是CIDR网络格式特别方便的地方:10.23.2.0/24匹配,并且其前缀长度为24位;0.0.0.0/0也匹配,但其前缀长度为0位(即没有前缀),因此10.23.2.0/24的规则优先。

NOTE The -n option tells route to show IP addresses instead of showing hosts and networks by name. This is an important option to remember because you’ll be able to use it in other network-related commands such as netstat.

注意:-n选项告诉route显示IP地址,而不是按名称显示主机和网络。这是一个重要的选项,因为您将能够在其他与网络相关的命令(如netstat)中使用它。

$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.23.2.1 0.0.0.0 UG 0 0 0 eth0
10.23.2.0 0.0.0.0 255.255.255.0 U 1 0 0 eth0

9.4.1 The Default Gateway(默认网关)

An entry for 0.0.0.0/0 in the routing table has special significance because it matches any address on the Internet. This is the default route, and the address configured under the Gateway column (in the route - n output) in the default route is the default gateway. When no other rules match, the default route always does, and the default gateway is where you send messages when there is no other choice. You can configure a host without a default gateway, but it won’t be able to reach hosts outside the destinations in the routing table

路由表中0.0.0.0/0的条目具有特殊意义,因为它匹配互联网上的任何地址。

这是默认路由,而在默认路由中,网关列(在route -n输出中)下配置的地址就是默认网关。

当没有其他规则匹配时,默认路由总是匹配,并且当没有其他选择时,消息将发送到默认网关。

您可以配置一个没有默认网关的主机,但它将无法到达路由表中目的地之外的主机。

NOTE On most networks with a netmask of 255.255.255.0, the router is usually at address 1 of the subnet (for example, 10.23.2.1 in 10.23.2.0/24). Because this is simply a convention, there can be exceptions.

注意:在大多数子网掩码为255.255.255.0的网络上,路由器通常位于子网的第一个地址(例如,在10.23.2.0/24中为10.23.2.1)。由于这只是一种约定,可能会有例外情况。

9.5 Basic ICMP and DNS Tools(基础 ICMP 和 DNS 工具)

Now it’s time to look at some basic practical utilities to help you interact with hosts. These tools use two protocols of particular interest: Internet Control Message Protocol (ICMP), which can help you root out problems with connectivity and routing, and the Domain Name Service (DNS) system, which maps names to IP addresses so that you don’t have to remember a bunch of numbers.

现在是时候看一些基本实用工具,帮助您与主机进行交互了。

这些工具使用两种特别重要的协议:Internet控制消息协议(ICMP),可以帮助您排除与连接和路由有关的问题;以及域名服务(DNS)系统,它将名称映射到IP地址,这样您就不必记住一堆数字了。

9.5.1 ping

ping (see http://ftp.arl.mil/~mike/ping.html) is one of the most basic network debugging tools. It sends ICMP echo request packets to a host that ask a recipient host to return the packet to the sender. If the recipient host gets the packet and is configured to reply, it sends an ICMP echo response packet in return.

ping(见http://ftp.arl.mil/~mike/ping.html)是最基本的网络调试工具之一。

它向一个主机发送ICMP回显请求数据包,要求接收方主机将数据包返回给发送方。

如果接收方主机接收到数据包并配置为回复,则会返回一个ICMP回显响应数据包。

For example, say that you run ping 10.23.2.1 and get this output:

例如,假设您运行ping 10.23.2.1并获得以下输出:

$ ping 10.23.2.1
PING 10.23.2.1 (10.23.2.1) 56(84) bytes of data.
64 bytes from 10.23.2.1: icmp_req=1 ttl=64 time=1.76 ms
64 bytes from 10.23.2.1: icmp_req=2 ttl=64 time=2.35 ms
64 bytes from 10.23.2.1: icmp_req=4 ttl=64 time=1.69 ms
64 bytes from 10.23.2.1: icmp_req=5 ttl=64 time=1.61 ms

The first line says that you’re sending 56-byte packets (84 bytes, if you include the headers) to 10.23.2.1 (by default, one packet per second), and the remaining lines indicate responses from 10.23.2.1. The most important parts of the output are the sequence number (icmp_req) and the round-trip time (time). The number of bytes returned is the size of the packet sent plus 8. (The content of the packets isn’t important to you.)

第一行表示您正在向10.23.2.1发送56字节的数据包(如果包括头部,则为84字节,默认情况下,每秒发送一个数据包),其余行表示来自10.23.2.1的响应。

输出的最重要部分是序列号(icmp_req)和往返时间(time)。

返回的字节数是发送的数据包的大小加上8个字节(数据包的内容对您来说不重要)。

A gap in the sequence numbers, such as the one between 2 and 4, usually means there’s some kind of connectivity problem. It’s possible for packets to arrive out of order, and if they do, there’s some kind of problem because ping sends only one packet a second. If a response takes more than a second (1000ms) to arrive, the connection is extremely slow.

序列号之间的间隔,比如2和4之间的间隔,通常意味着存在某种连接问题。

数据包可能会无序到达,如果确实如此,则表示存在某种问题,因为ping每秒只发送一个数据包。如果响应的到达时间超过一秒(1000ms),则连接非常慢。

The round-trip time is the total elapsed time between the moment that the request packet leaves and moment that the response packet arrives. If there’s no way to reach the destination, the final router to see the packet returns an ICMP “host unreachable” packet to ping.

往返时间是请求数据包离开和响应数据包到达之间的总耗时。

如果无法到达目标地点,则最后一个路由器将返回一个ICMP“主机不可达”数据包给ping。

On a wired LAN, you should expect absolutely no packet loss and very low numbers for the round-trip time. (The preceding example output is from a wireless network.) You should also expect no packet loss from your network to and from your ISP and reasonably steady round-trip times.

在有线局域网上,您应该预期没有任何数据包丢失,并且往返时间非常低。

(上述示例输出来自无线网络。)您还应该预期从您的网络到ISP以及从ISP返回的往返时间没有数据包丢失并且相对稳定。

NOTE For security reasons, not all hosts on the Internet respond to ICMP echo request packets, so you might find that you can connect to a website on a host but not get a ping response.

注意:出于安全原因,并非所有互联网上的主机都会响应ICMP回显请求数据包,因此您可能会发现您可以连接到主机上的网站,但无法获得ping的响应。

9.5.2 traceroute

The ICMP-based program traceroute will come in handy when you reach the material on routing later in this chapter. Use traceroute host to see the path your packets take to a remote host. (traceroute -n host will disable hostname lookups.)

基于 ICMP 的程序 traceroute 将在本章后面的路由材料中派上用场。

使用 traceroute host 查看数据包到达远程主机的路径。

(traceroute -n host 将禁用主机名查询)。

One of the best things about traceroute is that it reports return trip times at each step in the route, as demonstrated in this output fragment:

traceroute 的一大优点是,它能报告路由中每一步的回程时间,如输出片段所示:

4 206.220.243.106 1.163 ms 0.997 ms 1.182 ms
5 4.24.203.65 1.312 ms 1.12 ms 1.463 ms
6 64.159.1.225 1.421 ms 1.37 ms 1.347 ms
7 64.159.1.38 55.642 ms 55.625 ms 55.663 ms
8 209.247.10.230 55.89 ms 55.617 ms 55.964 ms
9 209.244.14.226 55.851 ms 55.726 ms 55.832 ms
10 209.246.29.174 56.419 ms 56.44 ms 56.423 ms

Because this output shows a big latency jump between hops 6 and 7, that part of the route is probably some sort of long-distance link.

由于输出结果显示第 6 跳和第 7 跳之间的延迟跳跃很大,因此这部分路由可能是某种长途链路。

The output from traceroute can be inconsistent. For example, the replies may time out at a certain step, only to “reappear” in later steps. The reason is usually that the router at that step refused to return the debugging output that traceroute wants but routers in later steps were happy to return the output. In addition, a router might choose to assign a lower priority to the debugging traffic than it does to normal traffic.

traceroute 的输出可能不一致。

例如,回复可能在某一步超时,但在后面的步骤中又 "重新出现"。

原因通常是该步骤的路由器拒绝返回 traceroute 所需的调试输出,但后面步骤的路由器却乐意返回输出。

此外,路由器可能会选择为调试流量分配比正常流量更低的优先级。

9.5.3 DNS and host

IP addresses are difficult to remember and subject to change, which is why we normally use names such as www.example.com instead. The DNS library on your system normally handles this translation automatically, but sometimes you’ll want to manually translate between a name and an IP address. To find the IP address behind a domain name, use the host command:

IP地址很难记住,并且可能会发生变化,这就是为什么我们通常使用诸如www.example.com之类的名称。

您的系统上的DNS库通常会自动处理这种转换,但有时您需要手动在名称和IP地址之间进行转换。

要查找域名背后的IP地址,请使用host命令:

$ host www.example.com
www.example.com has address 93.184.216.119
www.example.com has IPv6 address 2606:2800:220:6d:26bf:1447:1097:aa7

Notice how this example has both the IPv4 address 93.184.216.119 and the much larger IPv6 address. This means that this host also has an address on the next-generation version of the Internet.

请注意,此示例中既有IPv4地址93.184.216.119,也有更大的IPv6地址。

这意味着该主机还在下一代互联网版本上有一个地址。

You can also use host in reverse: Enter an IP address instead of a hostname to try to discover the hostname behind the IP address. But don’t expect this to work reliably. Many hostnames can represent a single IP address, and DNS doesn’t know how to determine which hostname should correspond to an IP address. The domain administrator must manually set up this reverse lookup, and often the administrator does not. (There is a lot more to DNS than the host command. We’ll cover basic client configuration later in 9.12 Resolving Hostnames.)

您也可以反向使用host:输入IP地址而不是主机名,尝试发现IP地址背后的主机名。

但不要指望这能可靠地工作。

许多主机名可以表示一个IP地址,并且DNS不知道如何确定哪个主机名应对应一个IP地址。

域名管理员必须手动设置这种反向查找,而且通常管理员并不这样做。

(DNS比host命令复杂得多。我们将在9.12解析主机名中介绍基本的客户端配置。)

9.6 The Physical Layer and Ethernet(物理层和以太网)

One of the key things to understand about the Internet is that it’s a software network. Nothing we’ve discussed so far is hardware specific, and indeed, one reason for the Internet’s success is that it works on almost any kind of computer, operating system, and physical network. However, you still have to put a network layer on top of some kind of hardware, and that interface is called the physical layer.

互联网的一个关键要点是它是一个软件网络。到目前为止,我们讨论的内容都与硬件无关,事实上,互联网之所以成功,其中一个原因就是它可以在几乎任何类型的计算机、操作系统和物理网络上运行。

然而,你仍然需要在某种硬件上放置一个网络层,这个接口被称为物理层。

In this book, we’ll look at the most common kind of physical layer: an Ethernet network. The IEEE 802 family of standards documents defines many different kinds of Ethernet networks, from wired to wireless, but they all have a few things in common, in particular, the following:

在本书中,我们将介绍最常见的物理层类型:以太网。

IEEE 802系列标准文件定义了许多不同类型的以太网,从有线到无线都有,但它们都有一些共同点,尤其是以下几点:

o All devices on an Ethernet network have a Media Access Control (MAC) address, sometimes called a hardware address. This address is independent of a host’s IP address, and it is unique to the host’s Ethernet network (but not necessarily a larger software network such as the Internet). A sample MAC address is 10:78:d2:eb:76:97.
o Devices on an Ethernet network send messages in frames, which are wrappers around the data sent. A frame contains the origin and destination MAC addresses.

  • 以太网上的所有设备都有一个媒体访问控制(MAC)地址,有时也称为硬件地址。这个地址与主机的IP地址无关,它是主机的以太网(但不一定是更大的软件网络,如互联网)上的唯一标识。一个示例MAC地址是10:78:d2:eb:76:97。
  • 以太网上的设备通过帧来发送消息,帧是发送的数据的包装器。一个帧包含了源和目的MAC地址。

Ethernet doesn’t really attempt to go beyond hardware on a single network. For example, if you have two different Ethernet networks with one host attached to both networks (and two different network interface devices), you can’t directly transmit a frame from one Ethernet network to the other unless you set up a special Ethernet bridge. And this is where higher network layers (such as the Internet layer) come in. By convention, each Ethernet network is also usually an Internet subnet. Even though a frame can’t leave one physical network, a router can take the data out of a frame, repackage it, and send it to a host on a different physical network, which is exactly what happens on the Internet.

以太网并不试图超越单个网络上的硬件。

例如,如果你有两个不同的以太网,一个主机连接在这两个网络上(并且有两个不同的网络接口设备),你不能直接将一个帧从一个以太网传输到另一个以太网,除非你设置一个特殊的以太网桥接器。

这就是更高级的网络层(如互联网层)的作用所在。

按照惯例,每个以太网通常也是一个互联网子网。

即使一个帧不能离开一个物理网络,路由器可以将数据从帧中取出,重新封装,并发送到不同物理网络上的主机,这正是在互联网上发生的情况。

9.7 Understanding Kernel Network Interfaces(理解内核网络接口)

The physical and the Internet layers must be connected in a way that allows the Internet layer to retain its hardware-independent flexibility. The Linux kernel maintains its own division between the two layers and provides communication standards for linking them called a (kernel) network interface. When you configure a network interface, you link the IP address settings from the Internet side with the hardware identification on the physical device side. Network interfaces have names that usually indicate the kind of hardware underneath, such as eth0 (the first Ethernet card in the computer) and wlan0 (a wireless interface).

物理层和互联网层必须以一种方式连接在一起,以使互联网层保持其硬件无关的灵活性。

Linux内核在这两个层之间保持了自己的划分,并提供了用于连接它们的通信标准,称为(内核)网络接口。

当您配置网络接口时,将互联网端的IP地址设置与物理设备端的硬件标识进行链接。

网络接口有一般指示底层硬件类型的名称,例如eth0(计算机中的第一个以太网卡)和wlan0(无线接口)。

In 9.3.1 Viewing Your Computer’s IP Addresses, you learned the most important command for viewing or manually configuring the network interface settings: ifconfig. Recall this output:

在9.3.1查看计算机的IP地址中,您学习了用于查看或手动配置网络接口设置的最重要的命令:ifconfig。回想一下这个输出:

eth0 Link encap:Ethernet HWaddr 10:78:d2:eb:76:97
 inet addr:10.23.2.4 Bcast:10.23.2.255 Mask:255.255.255.0
 inet6 addr: fe80::1278:d2ff:feeb:7697/64 Scope:Link
 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
 RX packets:85076006 errors:0 dropped:0 overruns:0 frame:0
 TX packets:68347795 errors:0 dropped:0 overruns:0 carrier:0
 collisions:0 txqueuelen:1000
 RX bytes:86427623613 (86.4 GB) TX bytes:23437688605 (23.4 GB)
 Interrupt:20 Memory:fe500000-fe520000

For each network interface, the left side of the output shows the interface name, and the right side contains settings and statistics for the interface. In addition to the Internet layer pieces that we’ve already covered, you also see the MAC address on the physical layer (HWaddr). The lines containing UP and RUNNING tell you that the interface is working.

对于每个网络接口,输出的左侧显示接口名称,右侧包含接口的设置和统计信息。

除了我们已经介绍过的互联网层部分,您还可以看到物理层上的MAC地址(HWaddr)。

包含UP和RUNNING的行告诉您接口正在工作。

Although ifconfig shows some hardware information (in this case, even some low-level device settings such as the interrupt and memory used), it’s designed primarily for viewing and configuring the software layers attached to the interfaces. To dig deeper into the hardware and physical layer behind a network interface, use something like the ethtool command to display or change the settings on Ethernet cards. (We’ll look briefly at wireless networks in 9.23 Wireless Ethernet.)

尽管ifconfig显示了一些硬件信息(在这种情况下,甚至包括一些低级设备设置,如中断和内存使用),但它主要设计用于查看和配置与接口连接的软件层。

要更深入地了解网络接口背后的硬件和物理层,请使用类似ethtool命令来显示或更改以太网卡上的设置。

(我们将在9.23无线以太网中简要介绍无线网络。)

9.8 Introduction to Network Interface Configuration(网络接口配置介绍)

You’ve now seen all of the basic elements that go into the lower levels of a network stack: the physical layer, the network (Internet) layer, and the Linux kernel’s network interfaces. In order to combine these pieces to connect a Linux machine to the Internet, you or a piece of software must do the following:

你现在已经看到了构成网络协议栈较低层的所有基本元素:物理层、网络(互联网)层以及Linux内核的网络接口。

为了将这些部分组合起来将Linux机器连接到互联网,您或者一款软件必须执行以下操作:

  1. Connect the network hardware and ensure that the kernel has a driver for it. If the driver is present, ifconfig -a displays a kernel network interface corresponding to the hardware.
  2. Perform any additional physical layer setup, such as choosing a network name or password.
  3. Bind an IP address and netmask to the kernel network interface so that the kernel’s device drivers (physical layer) and Internet subsystems (Internet layer) can talk to each other.
  4. Add any additional necessary routes, including the default gateway
  5. 连接网络硬件并确保内核具有相应的驱动程序。

    1. 如果驱动程序存在,ifconfig -a命令将显示一个与硬件相对应的内核网络接口。
  6. 执行任何其他物理层设置,例如选择网络名称或密码。
  7. 将IP地址和子网掩码绑定到内核网络接口,以便内核的设备驱动程序(物理层)和互联网子系统(互联网层)可以进行通信。
  8. 添加任何其他必要的路由,包括默认网关。

When all machines were big stationary boxes wired together, this was relatively straightforward: The kernel did step 1, you didn’t need step 2, and you’d do step 3 with the ifconfig command and step 4 with the route command.

当所有机器都是大型固定箱子通过有线连接在一起时,这相对简单:内核完成第1步,您不需要第2步,您可以使用ifconfig命令执行第3步,使用route命令执行第4步。

To manually set the IP address and netmask for a kernel network interface, you’d do this:

要手动设置内核网络接口的IP地址和子网掩码,您可以执行以下操作:

# ifconfig interface address netmask mask

# ifconfig 接口名称 地址 子网掩码

Here, interface is the name of the interface, such as eth0. When the interface was up, you’d be ready to add routes, which was typically just a matter of setting the default gateway, like this:

这里,接口是接口的名称,例如eth0。

当接口启动时,您将准备好添加路由,通常只需设置默认网关,例如:

# route add default gw gw-address

# route add default gw 网关地址

The gw-address parameter is the IP address of your default gateway; it must be an address in a locally connected subnet defined by the address and mask settings of one of your network interfaces.

网关地址参数是默认网关的IP地址;它必须是由其中一个网络接口的地址和子网掩码设置定义的本地连接子网中的地址。

9.8.1 Manually Adding and Deleting Routes(手动添加和删除路由)

To remove a default gateway, run

要删除默认网关,请运行

# route del -net default

You can easily override the default gateway with other routes. For example, say your machine is on subnet 10.23.2.0/24, you want to reach a subnet at 192.168.45.0/24, and you know that 10.23.2.44 can act as a router for that subnet. Run this command to send traffic bound for 192.168.45.0 to that router:

你可以轻松地通过其他路由来覆盖默认网关。例如,假设你的机器位于子网10.23.2.0/24上,你想要访问一个位于子网192.168.45.0/24上的目标,并且你知道10.23.2.44可以作为该子网的路由器。

运行以下命令将流量发送到该路由器以前往192.168.45.0子网:

# route add -net 192.168.45.0/24 gw 10.23.2.44

You don’t need to specify the router in order to delete a route:

删除路由时无需指定路由器:

# route del -net 192.168.45.0/24

Now, before you go crazy with routes, you should know that messing with routes is often more complicated than it appears. For this particular example, you also have to make sure that the routing for all hosts on 192.163.45.0/24 can lead back to 10.23.2.0/24, or the first route you add is basically useless.

在你开始疯狂地调整路由之前,你应该知道,处理路由问题通常比看起来复杂得多。

对于这个特定的例子,你还必须确保192.163.45.0/24上所有主机的路由能够返回到10.23.2.0/24,否则你添加的第一条路由基本上是无用的。

Normally, you should keep things as simple as possible for your clients, setting up networks so that their hosts need only a default route. If you need multiple subnets and the ability to route between them, it’s usually best to configure the routers acting as the default gateways to do all of the work of routing between different local subnets. (You’ll see an example in 9.17 Configuring Linux as a Router.)

通常情况下,你应该尽量简化客户端的设置,设置网络使其主机只需要一个默认路由。

如果你需要多个子网并且能够在它们之间进行路由,通常最好配置充当默认网关的路由器来处理不同本地子网之间的路由工作。

(你将在9.17 配置Linux作为路由器中看到一个例子。)

9.9 Boot-Activated Network Configuration(启动激活的网络配置)

We’ve discussed ways to manually configure a network, and the traditional way to ensure the correctness of a machine’s network configuration was to have init run a script to run the manual configuration at boot time. This boils down to running tools like ifconfig and route somewhere in the chain of boot events. Many servers still do it this way.

我们已经讨论了手动配置网络的方法,确保机器的网络配置正确的传统方式是在启动时通过init运行脚本来运行手动配置。

这归结为在引导事件链中的某个位置运行ifconfig和route等工具。

许多服务器仍然以这种方式进行配置。

There have been many attempts in Linux to standardize configuration files for boot-time networking. The tools ifup and ifdown do so—for example, a boot script can (in theory) run ifup eth0 to run the correct ifconfig and route commands for the eth0 interface. Unfortunately, different distributions have completely different implementations of ifup and ifdown, and as a result, their configuration files are also completely different. Ubuntu, for example, uses the ifupdown suite with configuration files in /etc/network, and Fedora uses its own set of scripts with configuration in /etc/sysconfig/network-scripts.

Linux中已经有许多尝试标准化引导时网络配置文件的工具。

ifup和ifdown就是这样的工具,例如,引导脚本可以(理论上)运行ifup eth0来运行适用于eth0接口的正确ifconfig和route命令。

不幸的是,不同的发行版对ifup和ifdown有完全不同的实现,因此它们的配置文件也完全不同。

例如,Ubuntu使用ifupdown套件,配置文件位于/etc/network目录中,而Fedora使用其自己的一套脚本,配置文件位于/etc/sysconfig/network-scripts目录中。

You don’t need to know the details of these configuration files, and if you insist on doing it all by hand and bypass your distribution’s configuration tools, you can just look up the formats in manual pages such as ifup(8) and interfaces(5). But it is important to know that this type of boot-activated configuration is often not even used. You’ll most often see it for the local-host (or lo; see 9.13 Localhost) network interface but nothing else because it’s too inflexible to meet the needs of modern systems.

您不需要了解这些配置文件的详细信息,如果您坚持手动操作并绕过发行版的配置工具,您可以在手册页(如ifup(8)和interfaces(5))中查找格式。

但重要的是要知道,这种引导激活的配置通常甚至不被使用。

您最常见的只会看到它用于本地主机(或lo;参见9.13 本地主机)网络接口,而不会用于其他任何接口,因为它过于不灵活,无法满足现代系统的需求。

9.10 Problems with Manual and Boot-Activated Network Configuration(手动和启动引导网络配置存在的问题)

Although most systems used to configure the network in their boot mechanisms—and many servers still do— the dynamic nature of modern networks means that most machines don’t have static (unchanging) IP addresses. Rather than storing the IP address and other network information on your machine, your machine gets this information from somewhere on the local physical network when it first attaches to that network. Most normal network client applications don’t particularly care what IP address your machine uses, as long as it works. Dynamic Host Configuration Protocol (DHCP, described in 9.16 Understanding DHCP) tools do the basic network layer configuration on typical clients.

尽管大多数系统在引导机制中使用的方式来配置网络(许多服务器仍然如此),但现代网络的动态性意味着大多数计算机没有静态(不变的)IP地址。

您的计算机在首次连接到本地物理网络时,会从该网络的某个地方获取IP地址和其他网络信息,而不是将其存储在您的计算机上。

大多数普通网络客户端应用程序并不特别关心您的计算机使用的IP地址是什么,只要它能正常工作即可。

动态主机配置协议(DHCP,在9.16节“理解DHCP”中有描述)工具对典型客户端的基本网络层配置进行处理。

There’s more to the story, though. For example, wireless networks add additional dimensions to interface configuration, such as network names, authentication, and encryption techniques. When you step back to look at the bigger picture, you see that your system needs a way to answer the following questions:

然而,故事还有更多内容。

例如,无线网络为接口配置增加了其他维度,如网络名称、认证和加密技术。

当您回过头来看整个大局时,您会发现您的系统需要一种方式来回答以下问题:

o If the machine has multiple physical network interfaces (such as a notebook with wired and wireless Ethernet), how do you choose which one(s) to use?
o How should the machine set up the physical interface? For wireless networks, this includes scanning for network names, choosing a name, and negotiating authentication.
o Once the physical network interface is connected, how should the machine set up the software network layers, such as the Internet layer?
o How can you let a user choose connectivity options? For example, how do you let a user choose a wireless network?
o What should the machine do if it loses connectivity on a network interface?

  • 如果计算机具有多个物理网络接口(例如带有有线和无线以太网的笔记本电脑),您如何选择要使用的接口?
  • 计算机应该如何设置物理接口?对于无线网络,这包括扫描网络名称、选择名称和进行认证协商。
  • 一旦物理网络接口连接上了,计算机应该如何设置软件网络层,例如互联网层?
  • 如何让用户选择连接选项?例如,如何让用户选择无线网络?
  • 如果网络接口失去连接,计算机应该怎么办?

Answering these questions is usually more than simple boot scripts can handle, and it’s a real hassle to do it all by hand. The answer is to use a system service that can monitor physical networks and choose (and automatically configure) the kernel network interfaces based on a set of rules that makes sense to the user. The service should also be able to respond to requests from users, who should be able to change the wireless network they’re on without having to become root just to fiddle around with network settings every time something changes.

回答这些问题通常超出了简单的引导脚本的能力范围,而且手工完成这一切真的很麻烦。

答案是使用一个系统服务,该服务可以监视物理网络并根据一组对用户有意义的规则选择(并自动配置)内核网络接口。

该服务还应能够响应用户的请求,用户应能够在不必每次发生变化时都成为root用户来调整网络设置的情况下更改他们所在的无线网络。

9.11 Network Configuration Managers(网络配置管理器)

There are several ways to automatically configure networks in Linux-based systems. The most widely used option on desktops and notebooks is NetworkManager. Other network configuration management systems are mainly targeted for smaller embedded systems, such as OpenWRT’s netifd, Android’s ConnectivityManager service, ConnMan, and Wicd. We’ll briefly discuss NetworkManager because it’s the one you’re most likely to encounter. We won’t go into a tremendous amount of detail, though, because after you see the big picture, NetworkManager and other configuration systems will be more transparent

在基于Linux的系统中,有几种自动配置网络的方法。

在台式机和笔记本上,最常用的选项是NetworkManager。

其他网络配置管理系统主要针对较小的嵌入式系统,例如OpenWRT的netifd、Android的ConnectivityManager服务、ConnMan和Wicd。

我们将简要讨论NetworkManager,因为这是您最有可能遇到的。

虽然我们不会详细介绍,但在您了解整体情况之后,NetworkManager和其他配置系统将更加透明。

9.11.1 NetworkManager Operation(网络管理器操作)

NetworkManager is a daemon that the system starts upon boot. Like all daemons, it does not depend on a running desktop component. Its job is to listen to events from the system and users and to change the network configuration based on a bunch of rules.

NetworkManager是系统启动时系统启动的守护进程。与所有守护进程一样,它不依赖于运行的桌面组件。它的工作是监听来自系统和用户的事件,并根据一系列规则改变网络配置。

When running, NetworkManager maintains two basic levels of configuration. The first is a collection of information about available hardware devices, which it normally collects from the kernel and maintains by monitoring udev over the Desktop Bus (D-Bus). The second configuration level is a more specific list of connections: hardware devices and additional physical and network layer configuration parameters. For example, a wireless network can be represented as a connection.

运行时,NetworkManager维护两个基本级别的配置。

第一个是有关可用硬件设备的信息集合,通常它从内核中收集并通过监听udev在桌面总线(D-Bus)上维护。

第二个配置级别是更具体的连接列表:硬件设备和附加的物理和网络层配置参数。

例如,无线网络可以表示为一个连接。

To activate a connection, NetworkManager often delegates the tasks to other specialized network tools and daemons such as dhclient to get Internet layer configuration from a locally attached physical network. Because network configuration tools and schemes vary among distributions, NetworkManager uses plugins to interface with them, rather than imposing its own standard. There are plugins for the both the Debian/ Ubuntu and Red Hat–style interface configuration, for example.

为了激活一个连接,NetworkManager通常将任务委托给其他专门的网络工具和守护进程,例如使用dhclient从本地连接的物理网络获取Internet层配置。

由于网络配置工具和方案在不同的发行版中有所不同,NetworkManager使用插件与它们进行接口交互,而不是强加自己的标准。

例如,有适用于Debian/Ubuntu和Red Hat风格接口配置的插件。

Upon startup, NetworkManager gathers all available network device information, searches its list of connections, and then decides to try to activate one. Here’s how it makes that decision for Ethernet interfaces:

启动时,NetworkManager收集所有可用的网络设备信息,搜索其连接列表,然后决定尝试激活一个连接。以下是它在以太网接口上做出决策的方式:

  1. If a wired connection is available, try to connect using it. Otherwise, try the wireless connections.
  2. Scan the list of available wireless networks. If a network is available that you’ve previously connected to, NetworkManager will try it again.
  3. If more than one previously connected wireless networks are available, select the most recently connected.
  4. 如果有可用的有线连接,则尝试使用它进行连接。否则,尝试无线连接。
  5. 扫描可用无线网络列表。如果有一个以前连接过的网络可用,NetworkManager将再次尝试连接。
  6. 如果有多个以前连接过的无线网络可用,则选择最近连接的那个。

After establishing a connection, NetworkManager maintains it until the connection is lost, a better network becomes available (for example, you plug in a network cable while connected over wireless), or the user forces a change.

建立连接后,NetworkManager将保持连接直到连接丢失、有更好的网络可用(例如,您在无线连接的同时插入了网络电缆)或用户强制进行更改。

9.11.2 Interacting with NetworkManager

Most users interact with NetworkManager through an applet on the desktop—it’s usually an icon in the upper or lower right that indicates the connection status (wired, wireless, or not connected). When you click on the icon, you get a number of connectivity options, such as a choice of wireless networks and an option to disconnect from your current network. Each desktop environment has its own version of this applet, so it looks a little different on each one.、

大多数用户通过桌面上的一个小程序与NetworkManager进行交互——通常是位于右上角或右下角的一个图标,用于显示连接状态(有线、无线或未连接)。

当你点击这个图标时,会出现一系列的连接选项,比如选择无线网络和断开当前网络的选项。

每个桌面环境都有自己的这个小程序版本,所以在每个环境下都会有些许不同。

In addition to the applet, there are a few tools that you can use to query and control NetworkManager from your shell. For a very quick summary of your current connection status, use the nm-tool command with no arguments. You’ll get a list of interfaces and configuration parameters. In some ways, this is like ifconfig except that there’s more detail, especially when viewing wireless connections.

除了小程序之外,还有一些工具可以在命令行中查询和控制NetworkManager。

要快速查看当前连接状态的简要摘要,可以使用不带参数的nm-tool命令。

你将得到一个接口和配置参数的列表。在某些方面,这类似于ifconfig,但是显示的细节更多,特别是在查看无线连接时。

To control NetworkManager from the command line, use the nmcli command. This is a somewhat extensive command. See the nmcli(1) manual page for more information. Finally, the utility nm-online will tell you whether the network is up or down. If the network is up, the command returns zero as its exit code; it’s nonzero otherwise. (For more on how to use an exit code in a shell script, see Chapter 11.)

要通过命令行控制NetworkManager,可以使用nmcli命令。

这是一个相对复杂的命令。请参阅nmcli(1)手册页面获取更多信息。

最后,实用工具nm-online会告诉你网络是连接还是断开。

如果网络连接正常,该命令的退出代码将返回零;否则为非零。

(有关如何在shell脚本中使用退出代码的更多信息,请参阅第11章。)

9.11.3 NetworkManager Configuration

The general configuration directory for NetworkManager is usually /etc/NetworkManager, and there are several different kinds of configuration. The general configuration file is NetworkManager.conf. The format is similar to the XDG-style .desktop and Microsoft .ini files, with key-value parameters falling into different sections. You’ll find that nearly every configuration file has a [main] section that defines the plugins to use. Here’s a simple example that activates the ifupdown plugin used by Ubuntu and Debian:

NetworkManager的通用配置目录通常是/etc/NetworkManager,有几种不同类型的配置。

通用配置文件是NetworkManager.conf。

其格式类似于XDG风格的.desktop和Microsoft .ini文件,具有键-值参数分布在不同的部分中。

你会发现几乎每个配置文件都有一个[main]部分,用于定义要使用的插件。

以下是一个简单的示例,激活Ubuntu和Debian使用的ifupdown插件:

[main]
plugins=ifupdown,keyfile

Other distribution-specific plugins are ifcfg-rh (for Red Hat–style distributions) and ifcfg-suse (for SuSE). The keyfile plugin that you also see here supports NetworkManager’s native configuration file support. When using the plugin, you can see the system’s known connections in /etc/NetworkManager/system-connections.

其他特定于发行版的插件包括 ifcfg-rh(用于红帽风格的发行版)和 ifcfg-suse(用于SuSE)。

您在这里看到的 keyfile 插件支持 NetworkManager 的本地配置文件支持。

使用该插件时,您可以在 /etc/NetworkManager/system-connections 中看到系统已知的连接。

For the most part, you won’t need to change NetworkManager.conf because the more specific configuration options are found in other files.

在大多数情况下,您不需要更改 NetworkManager.conf,因为更具体的配置选项可以在其他文件中找到。

Unmanaged Interfaces

Although you may want NetworkManager to manage most of your network interfaces, there will be times when you want it to ignore interfaces. For example, there’s no reason why most users would need any kind of dynamic configuration on the localhost (lo) interface because the configuration never changes. You also want to configure this interface early in the boot process because basic system services often depend on it. Most distributions keep NetworkManager away from localhost.

尽管您可能希望NetworkManager管理大部分网络接口,但有时您希望它忽略某些接口。

例如,大多数用户不需要在本地回环(lo)接口上进行任何动态配置,因为该配置永远不会改变。您还希望在引导过程的早期配置此接口,因为基本系统服务通常依赖于它。

大多数发行版都将NetworkManager与本地回环隔离开来。

You can tell NetworkManager to disregard an interface by using plugins. If you’re using the ifupdown plugin (for example, in Ubuntu and Debian), add the interface configuration to your /etc/network/interfaces file and then set the value of managed to false in the ifupdown section of the NetworkManager.conf file:

您可以通过使用插件告诉NetworkManager忽略某个接口。

如果您正在使用ifupdown插件(例如,在Ubuntu和Debian中),请将接口配置添加到/etc/network/interfaces文件中,然后在NetworkManager.conf文件的ifupdown部分将managed的值设置为false:

[ifupdown]
managed=false

For the ifcfg-rh plugin that Fedora and Red Hat use, look for a line like this in the /etc/sysconfig/networkscripts directory that contains the ifcfg-* configuration files:

对于 Fedora 和 Red Hat 使用的 ifcfg-rh 插件,请在 /etc/sysconfig/network-scripts 目录中查找包含 ifcfg-* 配置文件的行,类似于这样的行:

NM_CONTROLLED=yes

If this line is not present or the value is set to no, NetworkManager ignores the interface. For example, you’ll find it deactivated in the ifcfg-lo file. You can also specify a hardware address to ignore, like this:

如果不存在这一行,或者该数值设置为“no”,NetworkManager 将忽略该接口。

例如,在 ifcfg-lo 文件中,你会发现它被停用了。你也可以指定一个要忽略的硬件地址,就像这样:

HWADDR=10:78:d2:eb:76:97

If you don’t use either of these network configuration schemes, you can still use the keyfile plugin to specify the unmanaged device directly inside your NetworkManager.conf file using the MAC address. Here’s how that might look:

如果您不使用这两种网络配置方案中的任何一种,仍然可以使用keyfile插件,通过MAC地址直接在NetworkManager.conf文件中指定未受管设备。下面是可能的示例:

[keyfile]
unmanaged-devices=mac:10:78:d2:eb:76:97;mac:1c:65:9d:cc:ff:b9

Dispatching

One final detail of NetworkManager configuration relates to specifiying additional system actions for when a network interface goes up or down. For example, some network daemons need to know when to start or stop listening on an interface in order to work correctly (such as the secure shell daemon discussed in the next chapter).

NetworkManager配置的最后一个细节与指定网络接口上下线时的其他系统操作有关。

例如,某些网络守护程序需要知道何时在接口上开始或停止监听,以便正常工作(如下一章中讨论的安全外壳守护程序)。

When the network interface status on a system changes, NetworkManager runs everything in /etc/NetworkManager/dispatcher.d with an argument such as up or down. This is relatively straightforward, but many distributions have their own network control scripts so they don’t place the individual dispatcher scripts in this directory. Ubuntu, for example, has just one script named 01ifupdown that runs everything in an appropriate subdirectory of /etc/network, such as /etc/network/if-up.d.

当系统上的网络接口状态发生变化时,NetworkManager会在/etc/NetworkManager/dispatcher.d中运行所有脚本,并带有up或down等参数。

这相对简单,但许多发行版都有自己的网络控制脚本,因此它们不会将各个调度程序脚本放在此目录中。

例如,Ubuntu只有一个名为01ifupdown的脚本,它会在/etc/network的适当子目录中运行所有脚本,如/etc/network/if-up.d。

As with the rest of the NetworkManager configuration, the details of these scripts are relatively unimportant; all you need to know is how to track down the appropriate location if you need to make an addition or change. As ever, don’t be shy about looking at scripts on your system.

与NetworkManager配置的其余部分一样,这些脚本的细节相对不重要;

你只需要知道如何找到适当的位置,以便在需要添加或更改时进行操作。

在查看系统上的脚本时,不要犹豫。

9.12 Resolving Hostnames

One of the final basic tasks in any network configuration is hostname resolution with DNS. You’ve already seen the host resolution tool that translates a name such as www.example.com to an IP address such as 10.23.2.132.

在任何网络配置中,主机名解析与DNS是最后一个基本任务之一。你已经看到了主机解析工具,它将诸如www.example.com这样的名称转换为诸如10.23.2.132这样的IP地址。

DNS differs from the network elements we’ve looked at so far because it’s in the application layer, entirely in user space. Technically, it is slightly out of place in this chapter alongside the Internet and physical layer discussion, but without proper DNS configuration, your Internet connection is practically worthless. No one in their right mind advertises IP addresses for websites and email addresses because a host’s IP address is subject to change and it’s not easy to remember a bunch of numbers. Automatic network configuration services such as DHCP nearly always include DNS configuration.

DNS与我们迄今为止所看到的网络元素不同,因为它位于应用层,完全在用户空间中。

从技术上讲,在本章中,它稍微有些不合适,因为没有正确的DNS配置,你的互联网连接几乎毫无价值。

没有人会为网站和电子邮件地址广告IP地址,因为主机的IP地址可能会改变,而且很难记住一堆数字。

自动网络配置服务(如DHCP)几乎总是包括DNS配置。

Nearly all network applications on a Linux system perform DNS lookups. The resolution process typically unfolds like this:

Linux系统上几乎所有的网络应用程序都执行DNS查找。解析过程通常如下:

  1. The application calls a function to look up the IP address behind a hostname. This function is in the system’s shared library, so the application doesn’t need to know the details of how it works or whether the implementation will change.
  2. When the function in the shared library runs, it acts according to a set of rules (found in /etc/nsswitch.conf) to determine a plan of action on lookups. For example, the rules usually say that even before going to DNS, check for a manual override in the /etc/hosts file.
  3. When the function decides to use DNS for the name lookup, it consults an additional configuration file to find a DNS name server. The name server is given as an IP address.
  4. The function sends a DNS lookup request (over the network) to the name server.
  5. The name server replies with the IP address for the hostname, and the function returns this IP address to the application.
  6. 应用程序调用一个函数来查找主机名背后的IP地址。这个函数在系统的共享库中,所以应用程序不需要知道它是如何工作的,也不需要知道实现是否会改变。
  7. 当共享库中的函数运行时,它根据一组规则(在/etc/nsswitch.conf中找到)来确定查找的行动计划。例如,这些规则通常会说,在去DNS之前,先在/etc/hosts文件中检查手动覆盖。
  8. 当函数决定使用DNS进行名称查找时,它会查询一个附加的配置文件来找到DNS名称服务器。名称服务器以IP地址的形式给出。
  9. 函数向名称服务器发送一个DNS查找请求(通过网络)。
  10. 名称服务器回复主机名的IP地址,函数将此IP地址返回给应用程序。

This is the simplified version. In a typical modern system, there are more actors attempting to speed up the transaction and/or add flexibility. Let’s ignore that for now and take a closer look at the basic pieces.

这是简化版本。在一个典型的现代系统中,有更多的参与者试图加速交易和/或增加灵活性。

现在我们先忽略这些,更仔细地看看基本的部分。

9.12.1 /etc/hosts

On most systems, you can override hostname lookups with the /etc/hosts file. It usually looks like this:

在大多数系统上,您可以通过/etc/hosts文件覆盖主机名查找。

它通常看起来像这样:

127.0.0.1 localhost
10.23.2.3 atlantic.aem7.net atlantic
10.23.2.4 pacific.aem7.net pacific
You’ll nearly always see the entry for localhost here (see 9.13 Localhost).

NOTE In the bad old days, there was one central hosts file that everyone copied to their own machine in order to stay up-to-date (see RFCs 606, 608, 623, and 625), but as the ARPANET/Internet grew, this quickly got out of hand.

注意 在过去的旧日子里,曾经有一个集中的hosts文件,每个人都要将其复制到自己的机器上以保持最新(请参见RFC 606、608、623和625),但随着ARPANET/互联网的发展,这很快就失控了。

9.12.2 resolv.conf

The traditional configuration file for DNS servers is /etc/resolv.conf. When things were simpler, a typical example might have looked like this, where the ISP’s name server addresses are 10.32.45.23 and 10.3.2.3:

DNS 服务器的传统配置文件是 /etc/resolv.conf。

在事情变得更简单的时候,一个典型的例子可能看起来像这样,其中ISP的名称服务器地址是 10.32.45.23 和 10.3.2.3:

search mydomain.example.com example.com
nameserver 10.32.45.23
nameserver 10.3.2.3

The search line defines rules for incomplete hostnames (just the first part of the hostname; for example, myserver instead of myserver.example.com). Here, the resolver library would try to look up host.mydomain.example.com and host.example.com. But things are usually no longer this straightforward. Many enhancements and modifications have been made to the DNS configuration.

search 行定义了不完整主机名的规则(只是主机名的第一部分;例如,myserver 而不是 myserver.example.com)。

在这里,解析器库会尝试查找 host.mydomain.example.com 和 host.example.com。

但事情通常不再那么简单。对 DNS 配置进行了许多增强和修改。

9.12.3 Caching and Zero-Configuration DNS

There are two main problems with the traditional DNS configuration. First, the local machine does not cache name server replies, so frequent repeated network access may be unnecessarily slow due to name server requests. To solve this problem, many machines (and routers, if acting as name servers) run an intermediate daemon to intercept name server requests and return a cached answer to name service requests if possible; otherwise, requests go to a real name server. Two of the most common such daemons for Linux are dnsmasq and nscd. You can also set up BIND (the standard Unix name server daemon) as a cache. You can often tell if you’re running a name server caching daemon when you see 127.0.0.1 (localhost) in your /etc/resolv.conf file or when you see 127.0.0.1 show up as the server if you run nslookup -debug host.

传统DNS配置存在两个主要问题。

首先,本地机器不会缓存名称服务器的响应,因此由于名称服务器请求,频繁的重复网络访问可能会变得不必要地缓慢。

为了解决这个问题,许多机器(以及充当名称服务器的路由器)运行一个中间守护程序来拦截名称服务器请求,并在可能的情况下返回缓存的答案以响应名称服务请求;否则,请求将发送到真正的名称服务器。

Linux中两个最常见的此类守护程序是dnsmasq和nscd。

您还可以将BIND(标准的Unix名称服务器守护程序)设置为缓存。

通常可以通过查看/etc/resolv.conf文件中的127.0.0.1(本地主机)或者通过运行nslookup -debug host时看到127.0.0.1显示为服务器来判断是否正在运行名称服务器缓存守护程序。

It can be a tricky to track down your configuration if you’re running a name server–caching daemon. By default, dnsmasq has the configuration file /etc/dnsmasq.conf, but your distribution may override that. For example, in Ubuntu, if you’ve manually set up an interface that’s set up by NetworkManager, you’ll find it in the appropriate file in /etc/NetworkManager/system-connections because when NetworkManager activates a connection, it also starts dnsmasq with that configuration. (You can override all of this by uncommenting the dnsmasq part of your NetworkManager.conf.)

如果您正在运行名称服务器缓存守护程序,要追踪您的配置可能会有些棘手。

默认情况下,dnsmasq的配置文件为/etc/dnsmasq.conf,但您的发行版可能会覆盖该文件。

例如,在Ubuntu中,如果您手动设置了一个由NetworkManager设置的接口,您将在/etc/NetworkManager/system-connections的适当文件中找到它,因为当NetworkManager激活连接时,它还会使用该配置启动dnsmasq。

(您可以取消注释NetworkManager.conf文件中关于dnsmasq部分以覆盖所有这些设置。)

The other problem with the traditional name server setup is that it can be particularly inflexible if you want to be able to look up names on your local network without messing around with a lot of network configuration. For example, if you set up a network appliance on your network, you’ll want to be able to call it by name immediately. This is part of the idea behind zero-configuration name service systems such as Multicast DNS (mDNS) and Simple Service Discovery Protocol (SSDP). If you want to find a host by name on the local network, you just broadcast a request over the network; if the host is there, it replies with its address. These protocols go beyond hostname resolution by also providing information about available services.

传统名称服务器设置的另一个问题是,如果您想要能够在本地网络上查找名称而不必处理大量网络配置,它可能会变得特别不灵活。

例如,如果您在网络上设置了一个网络设备,您希望能够立即通过名称调用它。这正是零配置名称服务系统(如多播DNS(mDNS)和简单服务发现协议(SSDP))背后的理念的一部分。

如果您想要在本地网络上通过名称查找主机,只需在网络上广播一个请求;如果主机存在,它将回复其地址。

这些协议不仅仅限于主机名解析,还提供有关可用服务的信息。

The most widely used Linux implementation of mDNS is called Avahi. You’ll often see mdns as a resolver option in /etc/nsswitch.conf, which we’ll now look at in more detail.

最广泛使用的Linux mDNS实现称为Avahi。

您经常会在/etc/nsswitch.conf中看到mdns作为解析器选项,我们现在将更详细地查看这个文件。

9.12.4 /etc/nsswitch.conf

The /etc/nsswitch.conf file controls several name-related precedence settings on your system, such as user and password information, but we’ll only talk about the DNS settings in this chapter. The file on your system should have a line like this:

/etc/nsswitch.conf 文件控制着系统中几个与名称相关的优先设置,比如用户和密码信息,但在本章中我们只会讨论 DNS 设置。

您的系统上的文件应该有这样一行:

hosts: files dns

Putting files ahead of dns here ensures that your system checks the /etc/hosts file for the hostname of your requested IP address before asking the DNS server. This is usually a good idea (especially for looking up localhost, as discussed below), but your /etc/hosts file should be as short as possible. Don’t put anything in there to boost performance; doing so will burn you later. You can put all the hosts within a small private LAN in /etc/hosts, but the general rule of thumb is that if a particular host has a DNS entry, it has no place in /etc/hosts. (The /etc/hosts file is also useful for resolving hostnames in the early stages of booting, when the network may not be available.)

在这里将 files 放在 dns 之前可以确保您的系统在向 DNS 服务器请求之前检查 /etc/hosts 文件中您请求的 IP 地址的主机名。

这通常是一个好主意(特别是用于查找 localhost,如下所讨论的),但是您的 /etc/hosts 文件应该尽可能简短。

不要在其中放置任何内容以提高性能;这样做以后会给您带来麻烦。

您可以将小型私有 LAN 中的所有主机放在 /etc/hosts 中,但一般的经验法则是,如果特定主机有 DNS 记录,那么它就不应该出现在 /etc/hosts 中。

(/etc/hosts 文件也可用于在引导的早期阶段解析主机名,当时网络可能还不可用。)

NOTE DNS is a broad topic. If you have any responsibility for domain names, read DNS and BIND, 5th edition, by Cricket Liu and Paul Albitz (O’Reilly, 2006).

注意 DNS 是一个广泛的主题。如果您对域名有任何责任,请阅读 Cricket Liu 和 Paul Albitz 合著的《DNS 和 BIND,第 5 版》(O'Reilly,2006年)。

9.13 Localhost

When running ifconfig, you’ll notice the lo interface:

lo Link encap:Local Loopback
 inet addr:127.0.0.1 Mask:255.0.0.0
 inet6 addr: ::1/128 Scope:Host
 UP LOOPBACK RUNNING MTU:16436 Metric:1

The lo interface is a virtual network interface called the loopback because it “loops back” to itself. The effect is that connecting to 127.0.0.1 is connecting to the machine that you’re currently using. When outgoing data to local-host reaches the kernel network interface for lo, the kernel just repackages it as incoming data and sends it back through lo.

lo接口是一个虚拟网络接口,被称为环回接口,因为它“回环”到自身。

其效果是连接到127.0.0.1实际上是连接到当前使用的机器。

当发往本地主机的出站数据到达lo的内核网络接口时,内核会将其重新打包为入站数据并通过lo发送回去。

The lo loopback interface is often the only place you’ll see static network configuration in boot-time scripts. For example, Ubuntu’s ifup command reads /etc/network/interfaces and Fedora uses /etc/sysconfig/networkinterfaces/ ifcfg-lo. You can often find the loopback device configuration by digging around in /etc with grep

lo回环接口通常是在启动时脚本中唯一会看到静态网络配置的地方。

例如,Ubuntu的ifup命令会读取/etc/network/interfaces,而Fedora使用/etc/sysconfig/networkinterfaces/ ifcfg-lo。

你可以通过在/etc目录中使用grep来找到回环设备的配置。

9.14 The Transport Layer: TCP, UDP, and Services(传输层:TCP、UDP和服务)

So far, we’ve only seen how packets move from host to host on the Internet— in other words, the where question from the beginning of the chapter. Now let’s start to answer the what question. It’s important to know how your computer presents the packet data it receives from other hosts to its running processes. It’s difficult and inconvenient for user-space programs to deal with a bunch of raw packets the way that the kernel can. Flexibility is especially important: More than one application should be able to talk to the network at the same time (for example, you might have email and several web clients running).

到目前为止,我们只看到了互联网上数据包从主机到主机的传输方式,也就是本章开头提到的“何处”的问题。

现在让我们开始回答“何物”的问题。了解你的计算机如何将从其他主机接收到的数据包呈现给正在运行的进程非常重要。

对于用户空间程序来说,以内核的方式处理一堆原始数据包是困难且不方便的。

灵活性尤为重要:一个以上的应用程序应该能够同时与网络进行通信(例如,您可能同时运行电子邮件和几个 web 客户端)。

Transport layer protocols bridge the gap between the raw packets of the Internet layer and the refined needs of applications. The two most popular transport protocols are the Transmission Control Protocol (TCP) and the User Datagram Protocol (UDP). We’ll concentrate on TCP because it’s by far the most common protocol in use, but we’ll also take a quick look at UDP.

传输层协议填补了互联网层原始数据包与应用程序精细需求之间的差距。

最常见的两种传输协议是传输控制协议(TCP)和用户数据报协议(UDP)。

我们将重点关注 TCP,因为它是目前使用最广泛的协议,但我们也会简单介绍一下 UDP。

9.14.1 TCP Ports and Connections

TCP provides for multiple network applications on one machine by means of network ports. A port is just a number. If an IP address is like the postal address of an apartment building, a port is like a mailbox number— it’s a further subdivision.

TCP通过网络端口提供了在一台机器上运行多个网络应用程序的功能。

端口只是一个数字。

如果IP地址就像公寓楼的邮寄地址,那么端口就像邮箱号码——是进一步的细分。

When using TCP, an application opens a connection (not to be confused with NetworkManager connections) between one port on its own machine and a port on a remote host. For example, an application such as a web browser could open a connection between port 36406 on its own machine and port 80 on a remote host. From the application’s point of view, port 36406 is the local port and port 80 is the remote port.

使用TCP时,应用程序在本机的一个端口和远程主机的一个端口之间建立连接(注意不要与NetworkManager的连接混淆)。

例如,一个网页浏览器应用程序可以在本机的36406端口和远程主机的80端口之间建立连接。

从应用程序的角度来看,36406端口是本地端口,80端口是远程端口。

You can identify a connection by using the pair of IP addresses and port numbers. To view the connections currently open on your machine, use netstat. Here’s an example that shows TCP connections: The -n option disables hostname (DNS) resolution, and -t limits the output to TCP.

可以通过使用一对IP地址和端口号来标识一个连接。要查看当前在您的机器上打开的连接,请使用netstat命令。

下面是一个显示TCP连接的示例:-n选项禁用主机名(DNS)解析,-t选项将输出限制为TCP。

$ netstat -nt
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 10.23.2.4:47626 10.194.79.125:5222 
ESTABLISHED
tcp 0 0 10.23.2.4:41475 172.19.52.144:6667 
ESTABLISHED
tcp 0 0 10.23.2.4:57132 192.168.231.135:22 
ESTABLISHED

The Local Address and Foreign Address fields show connections from your machine’s point of view, so the machine here has an interface configured at 10.23.2.4, and ports 47626, 41475, and 57132 on the local side are all connected. The first connection here shows port 47626 connected to port 5222 of 10.194.79.125.

本地地址和外部地址字段显示了从您机器的角度看的连接情况,所以这台机器在10.23.2.4配置了一个接口,本地端的端口47626、41475和57132都已连接。

这里的第一个连接显示了端口47626与10.194.79.125的5222端口连接。

9.14.2 Establishing TCP Connections

To establish a transport layer connection, a process on one host initiates the connection from one of its local ports to a port on a second host with a special series of packets. In order to recognize the incoming connection and respond, the second host must have a process listening on the correct port. Usually, the connecting process is called the client, and the listener is the called the server (more about this in Chapter 10).

要建立传输层连接,一个主机上的进程通过一系列特殊的数据包从其本地端口向第二个主机的一个端口发起连接。

为了识别传入的连接并作出响应,第二个主机必须在正确的端口上有一个正在监听的进程。

通常,发起连接的进程被称为客户端,而监听的进程被称为服务器(关于这个问题在第10章有更多详细介绍)。

The important thing to know about the ports is that the client picks a port on its side that isn’t currently in use, but it nearly always connects to some well-known port on the server side. Recall this output from the netstat command in the preceding section:

关于端口需要知道的重要事情是,客户端在自己的一侧选择一个当前未使用的端口,但几乎总是连接到服务器一侧的某个众所周知的端口。

请回忆一下前一节中netstat命令的输出:

Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 10.23.2.4:47626 10.194.79.125:5222 ESTABLISHED

With a little help, you can see that this connection was probably initiated by a local client to a remote server because the port on the local side (47626) looks like a dynamically assigned number, whereas the remote port (5222) is a well-known service (the Jabber or XMPP messaging service, to be specific).

通过一点帮助,你可以看出这个连接可能是由本地客户端发起的到远程服务器的连接,因为本地一侧的端口(47626)看起来像是一个动态分配的数字,而远程端口(5222)是一个众所周知的服务(具体来说是Jabber或XMPP消息服务)。

NOTE A dynamically assigned port is called an ephemeral port.

注意:动态分配的端口被称为临时端口。

However, if the local port in the output is well-known, a remote host probably initiated the connection. In this example, remote host 172.24.54.234 has connected to port 80 (the default web port) on the local host.

然而,如果输出中的本地端口是众所周知的,那么可能是远程主机发起了连接。

在这个例子中,远程主机172.24.54.234连接到了本地主机的80端口(默认的Web端口)。

Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 10.23.2.4:80 172.24.54.234:43035 ESTABLISHED

A remote host connecting to your machine on a well-known port implies that a server on your local machine is listening on this port. To confirm this, list all TCP ports that your machine is listening on with netstat:

远程主机连接到你的机器上的一个众所周知的端口意味着你本地机器上有一个服务器在监听这个端口。

为了确认这一点,使用netstat列出你的机器上所有正在监听的TCP端口:

$ netstat -ntl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN
tcp 0 0 127.0.0.1:53 0.0.0.0:* LISTEN
--snip--

The line with 0.0.0.0:80 as the local address shows that the local machine is listening on port 80 for connections from any remote machine. (A server can restrict the access to certain interfaces, as shown in the last line, where something is listening for connections only on the localhost interface.) To learn even more, use lsof to identify the specific process that’s listening (as discussed in 10.5.1 lsof).

本地地址为0.0.0.0:80的那一行显示本地机器正在监听来自任何远程机器的80端口的连接。

(服务器可以限制对某些接口的访问,就像最后一行所示,其中某个东西只在本地回环接口上监听连接)。

要了解更多信息,可以使用lsof来确定正在监听的具体进程(如10.5.1节中所讨论的)。

9.14.3 Port Numbers and /etc/services

How do you know if a port is a well-known port? There’s no single way to tell, but one good place to start is to look in /etc/services, which translates well-known port numbers into names. This is a plaintext file. You should see entries like this:

如何确定一个端口是否是一个众所周知的端口?没有单一的方法可以确定,但一个好的起点是查看 /etc/services 文件,该文件将众所周知的端口号转换为名称。这是一个纯文本文件。

你应该能看到像这样的条目:

ssh 22/tcp # SSH Remote Login Protocol
smtp 25/tcp
domain 53/udp

The first column is a name and the second column indicates the port number and the specific transport layer protocol (which can be other than TCP).

第一列是名称,第二列指示端口号和特定的传输层协议(可能不是 TCP)。

NOTE In addition to /etc/services, an online registry for ports at http://www.iana.org/ is governed by the RFC6335 network standards document.

注意 除了 /etc/services,还有一个在线端口注册表 http://www.iana.org/ 受 RFC6335 网络标准文件的管理。

On Linux, only processes running as the superuser can use ports 1 through 1023. All user processes may listen on and create connections from ports 1024 and up.

在 Linux 上,只有以超级用户身份运行的进程才能使用 1 到 1023 的端口。所有用户进程都可以监听和创建从 1024 及以上的端口的连接。

9.14.4 Characteristics of TCP

TCP is popular as a transport layer protocol because it requires relatively little from the application side. An application process only needs to know how to open (or listen for), read from, write to, and close a connection. To the application, it seems as if there are incoming and outgoing streams of data; the process is nearly as simple as working with a file.

TCP作为一种传输层协议非常受欢迎,因为它对应用程序的要求相对较少。

一个应用程序进程只需要知道如何打开(或监听)、读取、写入和关闭连接。

对于应用程序来说,似乎存在着输入和输出的数据流;这个过程几乎和处理文件一样简单。

However, there’s a lot of work to do behind the scenes. For one, the TCP implementation needs to know how to break an outgoing data stream from a process into packets. However, the hard part is knowing how to convert a series of incoming packets into an input data stream for processes to read, especially when incoming packets don’t necessarily arrive in the correct order. In addition, a host using TCP must check for errors: Packets can get lost or mangled when sent across the Internet, and a TCP implementation must detect and correct these situations. Figure 9-3 shows a simplification of how a host might use TCP to send a message.

然而,在幕后还有很多工作要做。首先,TCP实现需要知道如何将一个进程的输出数据流分成数据包。

然而,困难的部分是如何将一系列的输入数据包转换成进程可读的输入数据流,特别是当输入数据包不一定按照正确的顺序到达时。

此外,使用TCP的主机必须检查错误:在通过互联网发送时,数据包可能会丢失或损坏,TCP实现必须检测和纠正这些情况。

图9-3显示了一个主机如何使用TCP发送消息的简化示意图。

Luckily, you need to know next to nothing about this mess other than that the Linux TCP implementation is primarily in the kernel and that utilities that work with the transport layer tend to manipulate kernel data structures. One example is the IP Tables packet-filtering system discussed in 9.21 Firewalls.

幸运的是,你几乎不需要了解这个混乱的过程,只需要知道Linux TCP实现主要在内核中,并且与传输层相关的实用工具往往会操作内核数据结构。

一个例子是在9.21防火墙中讨论的IP Tables数据包过滤系统。

9.14.5 UDP

UDP is a far simpler transport layer than TCP. It defines a transport only for single messages; there is no data stream. At the same time, unlike TCP, UDP won’t correct for lost or out-of-order packets. In fact, although UDP has ports, it doesn’t even have connections! One host simply sends a message from one of its ports to a port on a server, and the server sends something back if it wants to. However, UDP does have error detection for data inside a packet; a host can detect if a packet gets mangled, but it doesn’t have to do anything about it.

UDP是比TCP更简单的传输层协议。

它仅为单个消息定义了传输方式,没有数据流。

与TCP不同的是,UDP不会纠正丢失或乱序的数据包。

实际上,尽管UDP有端口,但它甚至没有连接!一个主机只需从其端口向服务器的某个端口发送一条消息,如果服务器愿意,就会发送一些回应。

然而,UDP确实对数据包中的数据进行了错误检测;主机可以检测到数据包是否损坏,但它不必对此采取任何措施。

Where TCP is like having a telephone conversation, UDP is like sending a letter, telegram, or instant message (except that instant messages are more reliable). Applications that use UDP are often concerned with speed— sending a message as quickly as possible. They don’t want the overhead of TCP because they assume the network between two hosts is generally reliable. They don’t need TCP’s error correction because they either have their own error detection systems or simply don’t care about errors.

TCP就像进行电话对话一样,而UDP则像发送信件、电报或即时消息一样(除了即时消息更可靠)。

使用UDP的应用程序通常关注速度,尽快发送消息。

它们不希望有TCP的开销,因为它们假设两台主机之间的网络通常是可靠的。

它们不需要TCP的错误纠正,因为它们要么有自己的错误检测系统,要么根本不关心错误。

One example of an application that uses UDP is the Network Time Protocol (NTP). A client sends a short and simple request to a server to get the current time, and the response from the server is equally brief. Because the client wants the response as quickly as possible, UDP suits the application; if the response from the server gets lost somewhere in the network, the client can just resend a request or give up. Another example is video chat—in this case, pictures are sent with UDP—and if some pieces get lost along the way, the client on the receiving end compensates the best it can.

一个使用UDP的应用程序的例子是网络时间协议(NTP)。

客户端向服务器发送一个简短而简单的请求以获取当前时间,服务器的响应同样简短。

因为客户端希望尽快得到响应,所以UDP适合这种应用程序;如果服务器的响应在网络中丢失了,客户端可以重新发送请求或放弃。

另一个例子是视频聊天,这种情况下使用UDP发送图片,如果在传输过程中有一些片段丢失,接收端的客户端会尽力进行补偿。

Figure 9-3. Sending a message with TCP

Figure 9-3. Sending a message with TCP

图9-3. 使用TCP发送消息

NOTE The rest of this chapter deals with more advanced networking topics, such as network filtering and routers, as they relate to the lower network layers that we’ve already seen: physical, network, and transport. If you like, feel free to skip ahead to the next chapter to see the application layer where everything comes together in user space. You’ll see processes that actually use the network rather than just throwing around a bunch of addresses and packets.

注意:本章的其余部分将涉及更高级的网络主题,例如与我们已经了解的底层网络层(物理层、网络层和传输层)相关的网络过滤和路由器。

如果你愿意,可以直接跳到下一章,在用户空间中了解应用层,这是所有东西都在一起的地方。

你将看到实际使用网络的进程,而不仅仅是在地址和数据包之间来回传递。

9.15 Revisiting a Simple Local Network

We’re now going to look at additional components of the simple network introduced in 9.3 The Internet Layer. Recall that this network consists of one local area network as one subnet and a router that connects the subnet to the rest of the Internet. You’ll learn the following:

我们现在要看一下9.3节《互联网层》中介绍的简单网络的附加组件。

回想一下,这个网络由一个本地区域网络作为一个子网和一个连接该子网与互联网其余部分的路由器组成。您将学到以下内容:

o How a host on the subnet automatically gets its network configuration
o How to set up routing
o What a router really is
o How to know which IP addresses to use for the subnet
o How to set up firewalls to filter out unwanted traffic from the Internet

o 子网上的主机如何自动获取其网络配置
o 如何设置路由
o 路由器的真正含义
o 如何确定子网使用哪些IP地址
o 如何设置防火墙以过滤掉来自互联网的不需要的流量

Let’s start by learning how a host on the subnet automatically gets its network configuration.

让我们从学习子网上的主机如何自动获取其网络配置开始。

9.16 Understanding DHCP(理解 DHCP)

When you set a network host to get its configuration automatically from the network, you’re telling it to use the Dynamic Host Configuration Protocol (DHCP) to get an IP address, subnet mask, default gateway, and DNS servers. Aside from not having to enter these parameters by hand, DHCP has other advantages for a network administrator, such as preventing IP address clashes and minimizing the impact of network changes. It’s very rare to see a modern network that doesn’t use DHCP.

当您将网络主机设置为从网络自动获取配置时,您告诉它使用动态主机配置协议(DHCP)来获取IP地址、子网掩码、默认网关和DNS服务器。

除了不需要手动输入这些参数之外,DHCP对于网络管理员还有其他优点,例如防止IP地址冲突和减小网络变化的影响。

现代网络很少见不使用DHCP的情况。

For a host to get its configuration with DHCP, it must be able to send messages to a DHCP server on its connected network. Therefore, each physical network should have its own DHCP server, and on a simple network (such as the one in 9.3 The Internet Layer), the router usually acts as the DHCP server.

要使主机通过DHCP获取其配置,它必须能够向其连接的网络上的DHCP服务器发送消息。

因此,每个物理网络应该有自己的DHCP服务器,在简单的网络(如9.3节中的互联网层)中,路由器通常充当DHCP服务器。

NOTE When making an initial DHCP request, a host doesn’t even know the address of a DHCP server, so it broadcasts the request to all hosts (usually all hosts on its physical network).

When a machine asks a DHCP server for an IP address, it’s really asking for a lease on an address for a certain amount of time. When the lease is up, a client can ask to renew the lease.

注意:在进行初始DHCP请求时,主机甚至不知道DHCP服务器的地址,因此它将请求广播给所有主机(通常是其物理网络上的所有主机)。

当一台机器向DHCP服务器请求IP地址时,实际上是在请求租用一个地址一段时间。

租约到期后,客户端可以请求续租。

9.16.1 The Linux DHCP Client(Linux DHCP客户端)

Although there are many different kinds of network manager systems, nearly all use the Internet Software Consortium (ISC) dhclient program to do the actual work. You can test dhclient by hand on the command line, but before doing so you must remove any default gateway route. To run the test, simply specify the network interface name (here, it’s eth0):

虽然有很多不同种类的网络管理系统,但几乎所有系统都使用Internet Software Consortium(ISC)的dhclient程序来进行实际工作。

您可以在命令行上手动测试dhclient,但在此之前,您必须删除任何默认网关路由。

要运行测试,只需指定网络接口名称(这里是eth0):

# dhclient eth0

Upon startup, dhclient stores its process ID in /var/run/dhclient.pid and its lease information in /var/state/dhclient.leases.

启动时,dhclient将其进程ID存储在/var/run/dhclient.pid中,并将租约信息存储在/var/state/dhclient.leases中。

9.16.2 Linux DHCP Servers(Linux DHCP 服务器)

You can task a Linux machine with running a DHCP server, which provides a good amount of control over the addresses that it gives out. However, unless you’re administering a large network with many subnets, you’re probably better off using specialized router hardware that includes built-in DHCP servers.

你可以让 Linux 机器运行 DHCP 服务器,这样就能很好地控制它所提供的地址。

不过,除非你要管理的是一个有许多子网的大型网络,否则你最好使用内置 DHCP 服务器的专用路由器硬件。

Probably the most important thing to know about DHCP servers is that you want only one running on the same subnet in order to avoid problems with clashing IP addresses or incorrect configurations.

关于 DHCP 服务器,最重要的一点可能是,在同一子网中只运行一个 DHCP 服务器,以避免出现 IP 地址冲突或配置错误的问题。

9.17 Configuring Linux as a Router(将 Linux 配置为路由器。)

Routers are essentially just computers with more than one physical network interface. You can easily configure a Linux machine as a router.

路由器本质上只是拥有多个物理网络接口的计算机。

你可以轻松地将 Linux 机器配置为路由器。

For example, say you have two LAN subnets, 10.23.2.0/24 and 192.168.45.0/24. To connect them, you have a Linux router machine with three network interfaces: two for the LAN subnets and one for an Internet uplink, as shown in Figure 9-4. As you can see, this doesn’t look very different from the simple network example that we’ve used in the rest of this chapter.

例如,你有两个局域网子网:10.23.2.0/24 和 192.168.45.0/24。

为了连接这两个子网,你需要一台带有三个网络接口的 Linux 路由器:两个用于 LAN 子网,一个用于 Internet 上行链路,如图 9-4 所示。

如你所见,这与我们在本章其余部分使用的简单网络示例并无太大区别。

Figure 9-4. Two subnets joined with a router

Figure 9-4. Two subnets joined with a router

图 9-4. 用路由器连接的两个子网

The router’s IP addresses for the LAN subnets are 10.23.2.1 and 192.168.45.1. When those addresses are configured, the routing table looks something like this (the interface names might vary in practice; ignore the Internet uplink for now):

路由器的局域网子网 IP 地址为 10.23.2.1 和 192.168.45.1。

配置好这些地址后,路由表就会如下所示(接口名称在实践中可能会有所不同;暂时忽略 Internet 上行链路):

Destination Gateway Genmask Flags Metric Ref Use 
Iface
10.23.2.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
192.168.45.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1

Now let’s say that the hosts on each subnet have the router as their default gateway (10.23.2.1 for 10.23.2.0/24 and 192.168.45.1 for 192.168.45.0/24). If 10.23.2.4 wants to send a packet to anything outside of 10.23.2.0/24, it passes the packet to 10.23.2.1. For example, to send a packet from 10.23.2.4 (Host A) to 192.168.45.61 (Host E), the packet goes to 10.23.2.1 (the router) via its eth0 interface, then back out through the router’s eth1 interface.

现在假设每个子网的主机都将路由器设为默认网关(10.23.2.1用于10.23.2.0/24,192.168.45.1用于192.168.45.0/24)。

如果10.23.2.4想要向10.23.2.0/24之外的任何地方发送数据包,它会将数据包传递给10.23.2.1。

例如,要将数据包从10.23.2.4(主机A)发送到192.168.45.61(主机E),数据包会通过其eth0接口传递到10.23.2.1(路由器),然后再通过路由器的eth1接口返回。

However, by default, the Linux kernel does not automatically move packets from one subnet to another. To enable this basic routing function, you need to enable IP forwarding in the router’s kernel with this command:

然而,默认情况下,Linux内核不会自动将数据包从一个子网转发到另一个子网。

要启用这个基本的路由功能,您需要在路由器的内核中启用IP转发功能,可以使用以下命令:

# sysctl -w net.ipv4.ip_forward

As soon as you enter this command, the machine should start routing packets between the two subnets, assuming that the hosts on those subnets know to send their packets to the router you just created.

一旦输入了这个命令,机器应该开始在这两个子网之间路由数据包,前提是这些子网上的主机知道将它们的数据包发送到您刚刚创建的路由器。

To make this change permanent upon reboot, you can add it to your /etc/sysctl.conf file. Depending on your distribution, you may have the option to put it into a file in /etc/sysctl.d so that distribution updates won’t overwrite your changes.

为了使这个更改在重新启动后仍然有效,您可以将其添加到您的/etc/sysctl.conf文件中。

根据您的发行版,您可能可以将其放入/etc/sysctl.d目录中的一个文件中,这样发行版更新就不会覆盖您的更改。

# sysctl -w net.ipv4.ip_forward

9.17.1 Internet Uplinks(互联网上行链路)

When the router also has the third network interface with an Internet uplink, this same setup allows Internet access for all hosts on both subnets because they’re configured to use the router as the default gateway. But that’s where things get more complicated. The problem is that certain IP addresses such as 10.23.2.4 are not actually visible to the whole Internet; they’re on so-called private networks. To provide for Internet connectivity, you must set up a feature called Network Address Translation (NAT) on the router. The software on nearly all specialized routers does this, so there’s nothing out of the ordinary here, but let’s examine the problem of private networks in a bit more detail.

当路由器的第三个网络接口还带有互联网上行链路时,同样的设置可以让两个子网中的所有主机都能访问互联网,因为它们被配置为使用路由器作为默认网关。

但问题也就在这里变得复杂起来。

问题在于,某些 IP 地址(如 10.23.2.4)实际上并不对整个互联网可见;它们位于所谓的专用网络中。

为了提供互联网连接,你必须在路由器上设置一个名为网络地址转换(NAT)的功能。

几乎所有专用路由器上的软件都能做到这一点,所以这里并没有什么特别之处,但让我们更详细地研究一下专用网络的问题。

9.18 Private Networks(私人网络)

Say you decide to build your own network. You have your machines, router, and network hardware ready. Given what you know about a simple network so far, your next question is “What IP subnet should I use?”

假设您决定搭建自己的网络。您已经准备好了计算机、路由器和网络硬件。根据您对简单网络的了解,您接下来的问题是:“我应该使用什么IP子网?”

If you want a block of Internet addresses that every host on the Internet can see, you can buy one from your ISP. However, because the range of IPv4 addresses is very limited, this costs a a lot and isn’t useful for much more than running a server that the rest of the Internet can see. Most people don’t really need this kind of service because they access the Internet as a client.

如果您想要一组所有互联网上的主机都能看到的互联网地址,您可以从您的ISP购买一个。

然而,由于IPv4地址范围非常有限,这样做成本很高,并且除了运行一个可以被互联网上的其他主机看到的服务器之外,没有太多其他用途。

大多数人实际上并不需要这种服务,因为他们作为客户端访问互联网。

The conventional, inexpensive alternative is to pick a private subnet from addresses in the RFC 1918/6761 Internet standards documents, shown in Table 9-2.the

传统的廉价方法是从 RFC 1918/6761 互联网标准文件中的地址中选择一个专用子网,如表 9-2 所示。

Table 9-2. Private Networks Defined by RFC 1918 and 6761

表9-2. RFC 1918和6761定义的私有网络

Table 9-2. Private Networks Defined by RFC 1918 and 6761

You can carve up private subnets as you wish. Unless you plan to have more than 254 hosts on a single network, pick a small subnet like 10.23.2.0/24, as we’ve been using throughout this chapter. (Networks with this netmask are sometimes called class C subnets. Although the term is technically somewhat obsolete, it’s still useful.)

您可以根据需求划分私有子网。

除非您计划在单个网络上拥有超过254个主机,否则选择一个小的子网,例如10.23.2.0/24,正如我们在本章中一直使用的那样。

(具有这个网络掩码的网络有时被称为C类子网。尽管这个术语在技术上有些过时,但仍然有用。)

What’s the catch? Hosts on the real Internet know nothing about private subnets and will not send packets to them, so without some help, hosts on private subnets cannot talk to the outside world. A router connected to the Internet (with a true, nonprivate address) needs to have some way to fill in the gap between that connection and the hosts on a private network.

有什么问题吗?
真实互联网上的主机对私有子网一无所知,不会向其发送数据包,因此在没有帮助的情况下,私有子网上的主机无法与外部世界通信。

连接到互联网的路由器(具有真实的非私有地址)需要有一种方式来填补连接和私有网络上的主机之间的空白。

9.19 Network Address Translation (IP Masquerading)(网络地址转换(IP 伪装))

NAT is the most commonly used way to share a single IP address with a private network, and it’s nearly universal in home and small office networks. In Linux, the variant of NAT that most people use is known as IP masquerading.

NAT是最常用的一种方式,用于将单个IP地址与私有网络共享,几乎在家庭和小型办公网络中普遍使用。在Linux中,大多数人使用的NAT变体被称为IP伪装。

The basic idea behind NAT is that the router doesn’t just move packets from one subnet to another; it transforms them as it moves them. Hosts on the Internet know how to connect to the router, but they know nothing about the private network behind it. The hosts on the private network need no special configuration; the router is their default gateway.

NAT背后的基本思想是,路由器不仅仅是将数据包从一个子网转移到另一个子网;在转移数据包时,它还会对其进行转换。

互联网上的主机知道如何连接到路由器,但它们对其后面的私有网络一无所知。

私有网络上的主机不需要特殊配置;路由器是它们的默认网关。

The system works roughly like this:

系统的工作原理大致如下:

  1. A host on the internal private network wants to make a connection to the outside world, so it sends its connection request packets through the router.
  2. The router intercepts the connection request packet rather than passing it out to the Internet (where it would get lost because the public Internet knows nothing about private networks).
  3. The router determines the destination of the connection request packet and opens its own connection to the destination.
  4. When the router obtains the connection, it fakes a “connection established” message back to the original internal host.
  5. The router is now the middleman between the internal host and the destination. The destination knows nothing about the internal host; the connection on the remote host looks like it came from the router.
  6. 内部私有网络上的主机想要与外部世界建立连接,因此它将连接请求数据包通过路由器发送出去。
  7. 路由器拦截连接请求数据包,而不是将其传递到互联网上(因为公共互联网对私有网络一无所知,所以数据包会丢失)。
  8. 路由器确定连接请求数据包的目标,并打开自己与目标之间的连接。
  9. 当路由器获得连接后,它向原始的内部主机发送一个伪造的“连接已建立”消息。
  10. 现在,路由器成为内部主机和目标之间的中间人。目标对内部主机一无所知;远程主机上的连接看起来像是来自路由器。

This isn’t quite as simple as it sounds. Normal IP routing knows only source and destination IP addresses in the Internet layer. However, if the router dealt only with the Internet layer, each host on the internal network could establish only one connection to a single destination at one time (among other limitations), because there is no information in the Internet layer part of a packet to distinguish multiple requests from the same host to the same destination. Therefore, NAT must go beyond the Internet layer and dissect packets to pull out more identifying information, particularly the UDP and TCP port numbers from the transport layers. UDP is fairly easy because there are ports but no connections, but the TCP transport layer is complex

这并不像听起来的那么简单。

普通的IP路由仅在互联网层中知道源IP地址和目标IP地址。

然而,如果路由器仅处理互联网层,那么内部网络上的每个主机一次只能与单个目标建立一个连接(还有其他限制),因为在数据包的互联网层部分没有信息可以区分来自同一主机到同一目标的多个请求。

因此,NAT必须超越互联网层,并解析数据包以提取更多的标识信息,特别是来自传输层的UDP和TCP端口号。

UDP相对比较简单,因为它有端口但没有连接,但TCP传输层则更为复杂。

In order to set up a Linux machine to perform as a NAT router, you must activate all of the following inside the kernel configuration: network packet filtering (“firewall support”), connection tracking, IP tables support, full NAT, and MASQUERADE target support. Most distribution kernels come with this support.

为了将Linux机器设置为执行NAT路由器的功能,您必须在内核配置中激活以下所有内容:网络数据包过滤(“防火墙支持”),连接跟踪,IP表支持,完整的NAT,以及MASQUERADE目标支持。

大多数发行版内核都带有这些支持。

Next you need to run some complex-looking iptables commands to make the router perform NAT for its private subnet. Here’s an example that applies to an internal Ethernet network on eth1 sharing an external connection at eth0 (you’ll learn more about the iptables syntax in 9.21 Firewalls):

接下来,您需要运行一些看起来复杂的iptables命令,以使路由器对其私有子网执行NAT。

以下是一个示例,适用于在eth1上共享外部连接的内部以太网网络(您将在9.21防火墙中了解更多关于iptables语法的内容):

# sysctl -w net.ipv4.ip_forward
# iptables -P FORWARD DROP
# iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# iptables -A FORWARD -i eth0 -o eth1 -m state --state 
ESTABLISHED,RELATED -j ACCEPT
# iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT

NOTE Although NAT works well in practice, remember that it’s essentially a hack used to extend the lifetime of the IPv4 address space. In a perfect world, we would all be using IPv6 (the nextgeneration Internet) and using its larger and more sophisticated address space without any pain.

注意:
尽管NAT在实践中表现良好,但请记住,它本质上是一种用于延长IPv4地址空间寿命的技巧。

在一个完美的世界中,我们都将使用IPv6(下一代互联网),利用它更大、更复杂的地址空间而无需任何痛苦。

You likely won’t ever need to use the commands above unless you’re developing your own software, especially with so much special-purpose router hardware available. But the role of Linux in a network doesn’t end here.

除非您正在开发自己的软件,尤其是有这么多专用路由器硬件可用,否则您可能永远不需要使用上述命令。

但是,Linux在网络中的作用并不止于此。

9.20 Routers and Linux(路由 和 Linux)

In the early days of broadband, users with less demanding needs simply connected their machine directly to the Internet. But it didn’t take long for many users to want to share a single broadband connection with their own networks, and Linux users in particular would often set up an extra machine to use as a router running NAT.

在宽带的早期阶段,那些需求不太高的用户只需将自己的机器直接连接到互联网。

但是很快,许多用户想要将单个宽带连接与自己的网络共享,尤其是Linux用户经常会设置一台额外的机器作为运行NAT的路由器。

Manufacturers responded to this new market by offering specialized router hardware consisting of an efficient processor, some flash memory, and several network ports—with enough power to manage a typical simple network, run important software such as a DHCP server, and use NAT. When it came to software, many manufacturers turned to Linux to power their routers. They added the necessary kernel features, stripped down the user-space software, and created GUI-based administration interfaces.

制造商为了满足这个新市场需求,推出了专门的路由器硬件,包括高效的处理器、一些闪存和几个网络端口,具备足够的能力来管理典型的简单网络、运行重要的软件如DHCP服务器,并使用NAT。

在软件方面,许多制造商选择了Linux作为路由器的操作系统。

他们添加了必要的内核功能,精简了用户空间软件,并创建了基于GUI的管理界面。

Almost as soon as the first of these routers appeared, many people became interested in digging deeper into the hardware. One manufacturer, Linksys, was required to release the source code for its software under the terms of the license of one its components, and soon specialized Linux distributions such as OpenWRT appeared for routers. (The “WRT” in these names came from the Linksys model number.)

几乎在第一批这样的路由器出现后,很多人对硬件进行深入研究产生了兴趣。

其中一家制造商Linksys根据其一个组件的许可证条款被要求公开其软件的源代码,很快就出现了专门为路由器设计的Linux发行版,比如OpenWRT。

(这些名称中的“WRT”来自Linksys的型号编号。)

Aside from the hobbyist aspect, there are good reasons to use these distributions: They’re often more stable than the manufacturer firmware, especially on older router hardware, and they typically offer additional features. For example, to bridge a network with a wireless connection, many manufacturers require you to buy matching hardware, but with OpenWRT installed, the manufacturer and age of the hardware don’t really matter. This is because you’re using a truly open operating system on the router that doesn’t care what hardware you use as long as your hardware is supported.

除了业余爱好者的方面,使用这些发行版还有很好的理由:它们通常比制造商的固件更稳定,尤其是在旧的路由器硬件上,并且它们通常提供额外的功能。

例如,为了通过无线连接桥接网络,许多制造商要求你购买配套的硬件,但是如果安装了OpenWRT,制造商和硬件的年代实际上并不重要。

这是因为你在路由器上使用的是一个真正开放的操作系统,它不关心你使用的是什么硬件,只要你的硬件得到支持即可。

You can use much of the knowledge in this book to examine the internals of custom Linux firmware, though you’ll encounter differences, especially when logging in. As with many embedded systems, open firmware tends to use BusyBox to provide many shell features. BusyBox is a single executable program that offers limited functionality for many Unix commands such as the shell, ls, grep, cat, and more. (This saves a significant amount of memory.) In addition, the boot-time init tends to be very simple on embedded systems. However, you typically won’t find these limitations to be a problem, because custom Linux firmware often includes a web administration interface similar to what you’d see from a manufacturer.

你可以利用本书中的大部分知识来研究定制的Linux固件的内部结构,尽管你会遇到一些差异,特别是在登录时。

与许多嵌入式系统一样,开放固件通常使用BusyBox提供许多Shell功能。BusyBox是一个单一的可执行程序,为许多Unix命令(如shell、ls、grep、cat等)提供了有限的功能。

(这节省了大量的内存。)此外,嵌入式系统上的启动初始化过程通常非常简单。

然而,你通常不会发现这些限制是个问题,因为定制的Linux固件通常包含一个类似于制造商提供的Web管理界面。

9.21 Firewalls

Routers in particular should always include some kind of firewall to keep undesirable traffic out of your network. A firewall is a software and/or hardware configuration that usually sits on a router between the Internet and a smaller network, attempting to ensure that nothing “bad” from the Internet harms the smaller network. You can also set up firewall features for each machine where the machine screens all of its incoming and outgoing data at the packet level (as opposed to the application layer, where server programs usually try to perform some access control of their own). Firewalling on individual machines is sometimes called IP filtering.

特别是路由器,应该始终包含某种防火墙,以阻止不必要的流量进入您的网络。

防火墙是一种软件和/或硬件配置,通常位于路由器和较小网络之间,试图确保来自互联网的任何“坏”东西不会对较小网络造成伤害。

您还可以为每台机器设置防火墙功能,其中机器在数据包级别上筛选其所有传入和传出的数据(与应用层不同,应用程序通常尝试执行一些自己的访问控制)。

有时将在单独的机器上进行的防火墙操作称为IP过滤。

A system can filter packets when it

当系统进行以下操作时,它可以筛选数据包:

o receives a packet,
o sends a packet, or
o forwards (routes) a packet to another host or gateway. With no firewalling in place, a system just processes packets and sends them on their way. Firewalls put checkpoints for packets at the points of data transfer identified above. The checkpoints drop, reject, or accept packets, usually based on some of these criteria:
o The source or destination IP address or subnet
o The source or destination port (in the transport layer information)
o The firewall’s network interface

  • 接收数据包
  • 发送数据包
  • 转发(路由)数据包到另一个主机或网关。如果没有设置防火墙,系统只是处理数据包并将其发送出去。防火墙在数据传输点处设置数据包检查点。这些检查点通常根据以下一些标准来丢弃、拒绝或接受数据包:
  • 源IP地址或目标IP地址或子网
  • 源端口或目标端口(在传输层信息中)
  • 防火墙的网络接口

Firewalls provide an opportunity to work with the subsystem of the Linux kernel that processes IP packets. Let’s look at that now.

防火墙提供了与处理IP数据包的Linux内核子系统一起工作的机会。

现在让我们来看一下这个。

9.21.1 Linux Firewall Basics(Linux 防火墙基础知识)

In Linux, you create firewall rules in a series known as a chain. A set of chains makes up a table. As a packet moves through the various parts of the Linux networking subsystem, the kernel applies the rules in certain chains to the packets. For example, after receiving a new packet from the physical layer, the kernel activates rules in chains corresponding to input.

在Linux中,您可以通过一系列称为链的方式来创建防火墙规则。一组链构成了一个表。

当数据包在Linux网络子系统的各个部分之间移动时,内核会根据特定链中的规则对数据包进行处理。

例如,在从物理层接收到新数据包后,内核会激活与输入相对应的链中的规则。

All of these data structures are maintained by the kernel. The whole system is called iptables, with an iptables user-space command to create and manipulate the rules.

所有这些数据结构都由内核维护。整个系统被称为iptables,有一个iptables用户空间命令用于创建和操作规则。

NOTE There is a newer system called nftables that has a goal of replacing iptables, but as of this writing, iptables is the dominant system for firewalls.

注意:还有一个名为nftables的新系统旨在取代iptables,但截至本文写作时,iptables仍然是主要的防火墙系统。

Because there can be many tables—each with their own sets of chains, each of which can contain many rules— packet flow can become quite complicated. However, you’ll normally work primarily with a single table named filterthat controls basic packet flow. There are three basic chains in the filtertable: INPUT for incoming packets, OUTPUT for outgoing packets, and FORWARD for routed packets.

由于可以有多个表,每个表都有自己的一组链,每个链都可以包含多个规则,因此数据包流动可能会变得非常复杂。

然而,通常您主要使用一个名为filter的表来控制基本的数据包流动。

filter表中有三个基本链:INPUT用于传入的数据包,OUTPUT用于传出的数据包,FORWARD用于路由的数据包。

Figure 9-5 and Figure 9-6 show simplified flowcharts for where rules are applied to packets in the filter table. There are two figures because packets can either come into the system from a network interface (Figure 9-5) or be generated by a local process (Figure 9-6). As you can see, an incoming packet from the network can be consumed by a user process and may not reach the FORWARD chain or the OUTPUT chain. Packets generated by user processes won’t reach the INPUT or FORWARD chains

图9-5和图9-6显示了规则在filter表中应用于数据包的简化流程图。

之所以有两个图,是因为数据包可以通过网络接口进入系统(图9-5),也可以由本地进程生成(图9-6)。

正如您所见,从网络进入的数据包可能会被用户进程消耗掉,不会到达FORWARD链或OUTPUT链。由用户进程生成的数据包不会到达INPUT或FORWARD链。

Figure 9-6. Chain-processing sequence for incoming packets from a local process

Figure 9-6. Chain-processing sequence for incoming packets from a local process

图9-6. 来自本地进程的入站数据包的链处理序列

This gets more complicated because there are many steps along the way other than just these three chains. For example, packets are subject to PREROUTING and POSTROUTING chains, and chain processing can also occur at any of the three lower network levels. For a big diagram for everything that’s going on, search the Internet for “Linux netfilter packet flow,” but remember that these diagrams try to include every possible scenario for packet input and flow. It often helps to break the diagrams down by packet source, as in Figure 9- 5 and Figure 9-6.

这变得更加复杂,因为除了这三个链之外,还有许多步骤。

例如,数据包会经过PREROUTING和POSTROUTING链,而且链处理也可以发生在三个较低的网络层中的任何一个。

如果想要了解正在进行的所有内容的大图表,请在互联网上搜索“Linux netfilter packet flow”,但请记住,这些图表试图包含每种可能的数据包输入和流动情景。

将图表按数据包来源进行拆分通常会有所帮助,如图9-5和图9-6所示。

9.21.2 Setting Firewall Rules(设置防火墙规则)

Let’s look at how the IP tables system works in practice. Start by viewing the current configuration with this command:

让我们来看看IP表系统在实践中是如何工作的。首先通过以下命令查看当前配置:

# iptables -L

The output is usually an empty set of chains, as follows:

通常输出为空链集,如下所示:

Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination

Each firewall chain has a default policy that specifies what to do with a packet if no rule matches the packet. The policy for all three chains in this example is ACCEPT, meaning that the kernel allows the packet to pass through the packet-filtering system. The DROP policy tells the kernel to discard the packet. To set the policy on a chain, use iptables -P like this:

每个防火墙链都有一个默认策略,指定如果没有规则匹配数据包时该如何处理数据包。

在这个例子中,所有三个链的策略都是 ACCEPT,表示内核允许数据包通过数据包过滤系统。

DROP 策略告诉内核丢弃数据包。

要设置链上的策略,请使用 iptables -P 命令,如下所示:

# iptables -P FORWARD DROP

WARNING Don’t do anything rash with the policies on your machine until you’ve read through the rest of this section

警告:在仔细阅读完本节剩余内容之前,请不要随意更改您机器上的策略。

Say that someone at 192.168.34.63 is annoying you. To prevent them from talking to your machine, run this command:

假设有人在 192.168.34.63 上让您感到不悦。

为阻止他们与您的机器通讯,请运行以下命令:

# iptables -A INPUT -s 192.168.34.63 -j DROP

The -A INPUT parameter appends a rule to the INPUT chain. The -s 192.168.34.63 part specifies the source IP address in the rule, and -j DROP tells the kernel to discard any packet matching the rule. Therefore, your machine will throw out any packet coming from 192.168.34.63.

-A INPUT参数将规则附加到INPUT链。

其中-s 192.168.34.63部分指定规则中的源IP地址,而-j DROP告诉内核丢弃与规则匹配的任何数据包。

因此,你的机器将丢弃来自192.168.34.63的任何数据包。

To see the rule in place, run iptables -L:

要查看已设置的规则,请运行iptables -L:

Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.34.63 anywhere

Unfortunately, your friend at 192.168.34.63 has told everyone on his subnet to open connections to your SMTP port (TCP port 25). To get rid of that traffic as well, run

# iptables -A INPUT -s 192.168.34.0/24 -p tcp --destination-port 25 -j DROP

This example adds a netmask qualifier to the source address as well as -p tcp to specify TCP packets only. A further restriction, --destination-port 25, says that the rule should only apply to traffic to port 25. The IP table list for INPUT now looks like this:

这个例子在源地址上添加了一个netmask限定符,同时加上了-p tcp来指定仅限制TCP数据包。

进一步的限制是--destination-port 25,表示规则仅适用于流向端口25的流量。

现在,INPUT的IP表列表如下:

Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.34.63 anywhere
DROP tcp -- 192.168.34.0/24 anywhere tcp dpt:smtp

All is well until you hear from someone you know at 192.168.34.37 saying that they can’t send you email because you blocked their machine. Thinking that this is a quick fix, you run this command:

一切都很顺利,直到你收到来自你认识的某人(IP地址为192.168.34.37)的消息,说他们无法给你发邮件,因为你屏蔽了他们的设备。

认为这是一个快速解决方案,你运行了这个命令:

# iptables -A INPUT -s 192.168.34.37 -j ACCEPT

However, it doesn’t work. To see why, look at the new chain:

然而,这并不奏效。

要了解原因,请看新的链条:

Chain INPUT (policy ACCEPT)
target prot opt source destination
DROP all -- 192.168.34.63 anywhere
DROP tcp -- 192.168.34.0/24 anywhere tcp dpt:smtp
ACCEPT all -- 192.168.34.37 anywhere

The kernel reads the chain from top to bottom, using the first rule that matches.

内核从上到下读取链路,使用第一个匹配的规则。

The first rule does not match 192.168.34.37, but the second does, because it applies to all hosts from 192.168.34.1 to 192.168.34.254 and this second rule says to drop packets. When a rule matches, the kernel carries out the action and looks no further down in the chain. (You might notice that 192.168.34.37 can send packets to any port on your machine except port 25 because the second rule only applies to port 25.)

第一个规则不匹配192.168.34.37,但是第二个规则匹配,因为它适用于从192.168.34.1到192.168.34.254的所有主机,并且这个第二个规则指示丢弃数据包。

当规则匹配时,内核执行相应的动作,并且不再继续向下查找链路。

(你可能注意到192.168.34.37可以向你的机器的任意端口发送数据包,除了端口25,因为第二个规则只适用于端口25。)

The solution is to move the third rule to the top. First, delete the third rule with this command:

解决办法是将第三个规则移动到顶部。

首先,使用以下命令删除第三个规则:

# iptables -D INPUT 3

Then insert that rule at the top of the chain with iptables -I:

然后用 iptables -I 将该规则插入链的顶端:

# iptables -I INPUT -s 192.168.34.37 -j ACCEPT

To insert a rule elsewhere in a chain, put the rule number after the chain name (for example, iptables -I INPUT 4 ...).

要在链的其他位置插入规则,请在链名后加上规则编号(例如,iptables -I INPUT 4 ... )。

9.21.3 Firewall Strategies(防火墙策略)

Although the tutorial above showed you how to insert rules and how the kernel processes IP chains, we haven’t seen firewall strategies that actually work. Let’s talk about that now

尽管上面的教程向您展示了如何插入规则以及内核如何处理IP链,但我们还没有看到实际起作用的防火墙策略。现在让我们来谈谈这个问题。

There are two basic kinds of firewall scenarios: one for protecting individual machines (where you set rules in each machine’s INPUT chain) and one for protecting a network of machines (where you set rules in the router’s FORWARD chain). In both cases, you can’t have serious security if you use a default policy of ACCEPT and continuously insert rules to drop packets from sources that start to send bad stuff. You must allow only the packets that you trust and deny everything else.

防火墙有两种基本的场景:一种是保护单个机器的场景(在每台机器的INPUT链中设置规则),另一种是保护机器网络的场景(在路由器的FORWARD链中设置规则)。

在这两种情况下,如果您使用接受的默认策略并不断插入规则以丢弃来自开始发送不良内容的源的数据包,那么您将无法获得严格的安全性。

您必须仅允许您信任的数据包,并拒绝其他所有内容。

For example, say your machine has an SSH server on TCP port 22. There’s no reason for any random host to initiate a connection to any other port on your machine, and you shouldn’t give any such host a chance. To set that up, first set the INPUT chain policy to DROP:

例如,假设您的机器在TCP端口22上有一个SSH服务器。

任何随机主机都没有理由与您的机器的任何其他端口建立连接,您也不应该给予任何此类主机机会。

为了设置这一点,首先将INPUT链的策略设置为DROP:

# iptables -P INPUT DROP

To enable ICMP traffic (for ping and other utilities), use this line:

要启用 ICMP 流量(用于 ping 和其他实用程序),请使用这一行:

# iptables -A INPUT -p icmp -j ACCEPT

Make sure that you can receive packets you send to both your own network IP address and 127.0.0.1 (localhost). Assuming your host’s IP address is my_addr, do this:

确保您能接收到发送到自己网络 IP 地址和 127.0.0.1(localhost)的数据包。

假设主机的 IP 地址是 my_addr,请执行此操作:

# iptables -A INPUT -s 127.0.0.1 -j ACCEPT
# iptables -A INPUT -s my_addr -j ACCEPT

If you control your entire subnet (and trust everything on it), you can replace my_addr with your subnet address and subnet mask, for example, 10.23.2.0/24.

如果您控制着整个子网(并信任子网中的一切),则可以用子网地址和子网掩码替换 my_addr,例如 10.23.2.0/24。

Now, although you still want to deny incoming TCP connections, you still need to make sure that your host can make TCP connections to the outside world. Because all TCP connections start with a SYN (connection request) packet, if you let all TCP packets through that aren’t SYN packets, you’re still okay:

现在,尽管您仍想拒绝传入的 TCP 连接,但仍需确保您的主机能与外界建立 TCP 连接。

由于所有 TCP 连接都是以 SYN(连接请求)数据包开始的,因此如果您允许所有非 SYN 数据包的 TCP 数据包通过,就不会有问题:

# iptables -A INPUT -p tcp '!' --syn -j ACCEPT

Next, if you’re using remote UDP-based DNS, you must accept traffic from your name server so that your machine can look up names with DNS. Do this for all DNS servers in /etc/resolv.conf. Use this command (where the name server’s address is ns_addr):

接下来,如果使用的是基于 UDP 的远程 DNS,则必须接受来自名称服务器的流量,这样机器才能使用 DNS 查找名称。

对 /etc/resolv.conf 中的所有 DNS 服务器都要这样做。使用此命令(其中名称服务器地址为 ns_addr):

# iptables -A INPUT -p udp --source-port 53 -s ns_addr -j ACCEPT

And finally, allow SSH connections from anywhere:

最后,允许从任何地方进行 SSH 连接:

# iptables -A INPUT -p tcp --destination-port 22 -j ACCEPT

The preceding iptables settings work for many situations, including any direct connection (especially broadband) where an intruder is much more likely to port-scan your machine. You could also adapt these settings for a firewalling router by using the FORWARD chain instead of INPUT and using source and destination subnets where appropriate. For more advanced configurations, you may find a configuration tool such as Shorewall to be helpful.

前面的iptables设置适用于许多情况,包括任何直接连接(特别是宽带连接),在这种情况下,入侵者更有可能对您的计算机进行端口扫描。

您还可以通过在适当的地方使用源和目标子网,将这些设置适应于防火墙路由器,使用FORWARD链而不是INPUT链。

对于更高级的配置,您可能会发现Shorewall等配置工具很有帮助。

This discussion has only touched on security policy. Remember that the key idea is to permit only the things that you find acceptable, not to try to find and execute the bad stuff. Furthermore, IP firewalling is only one piece of the security picture. (You’ll see more in the next chapter.)

这次讨论只涉及安全策略。

请记住,关键思想是只允许您认为可以接受的事物,而不是试图找到并执行有害的东西。

此外,IP防火墙只是安全方案的一部分。(在下一章中您将看到更多内容。)

9.22 Ethernet, IP, and ARP(以太网,IP和ARP)

There is one interesting basic detail in the implementation of IP over Ethernet that we have yet to cover. Recall that a host must place an IP packet inside an Ethernet frame in order to transmit the packet across the physical layer to another host. Recall, too, that frames themselves do not include IP address information; they use MAC (hardware) addresses. The question is this: When constructing the Ethernet frame for an IP packet, how does the host know which MAC address corresponds to the destination IP address?

在实现以太网上的IP传输中,有一个有趣的基本细节我们还没有涉及到。

回想一下,为了将数据包通过物理层传输到另一个主机,主机必须将IP数据包放置在以太网帧中。

同样,帧本身不包含IP地址信息,而是使用MAC(硬件)地址。

问题是:在构建IP数据包的以太网帧时,主机如何知道哪个MAC地址对应于目标IP地址?

We don’t normally think about this question much because networking software includes an automatic system of looking up MAC addresses called Address Resolution Protocol (ARP). A host using Ethernet as its physical layer and IP as the network layer maintains a small table called an ARP cache that maps IP addresses to MAC addresses. In Linux, the ARP cache is in the kernel. To view your machine’s ARP cache, use the arp command. (As with many other network commands, the -n option here disables reverse DNS lookups.)

通常我们不会过多考虑这个问题,因为网络软件包含了一种自动查找MAC地址的系统,称为地址解析协议(ARP)。

一个使用以太网作为物理层和IP作为网络层的主机会维护一个小表,称为ARP缓存,用于将IP地址映射到MAC地址。

在Linux中,ARP缓存位于内核中。

要查看您机器的ARP缓存,请使用arp命令。

(与许多其他网络命令一样,此处的-n选项禁用了反向DNS查找。)

$ arp -n
Address Hwtype Hwaddr Flags Mask Iface
10.1.2.141 ether 00:11:32:0d:ca:82 C eth0
10.1.2.1 ether 00:24:a5:b5:a0:11 C eth0
10.1.2.50 ether 00:0c:41:f6:1c:99 C eth0

When a machine boots, its ARP cache is empty. So how do these MAC addresses get in the cache? It all starts when the machine wants to send a packet to another host. If a target IP address is not in an ARP cache, the following steps occur:

当一台机器启动时,它的ARP缓存是空的。

那么这些MAC地址是如何进入缓存的呢?

一切都始于机器想要向另一台主机发送数据包。

如果目标IP地址不在ARP缓存中,将会按照以下步骤进行:

  1. The origin host creates a special Ethernet frame containing an ARP request packet for the MAC address that corresponds to the target IP address.
  2. The origin host broadcasts this frame to the entire physical network for the target’s subnet.
  3. If one of the other hosts on the subnet knows the correct MAC address, it creates a reply packet and frame containing the address and sends it back to the origin. Often, the host that replies is the target host and is simply replying with its own MAC address.
  4. The origin host adds the IP-MAC address pair to the ARP cache and can proceed.
  5. 源主机创建一个特殊的以太网帧,其中包含一个用于对应目标IP地址的MAC地址的ARP请求数据包。
  6. 源主机将此帧广播到目标子网的整个物理网络。
  7. 如果子网上的其他主机知道正确的MAC地址,它将创建一个包含该地址的回复数据包和帧,并将其发送回源主机。通常,回复的主机就是目标主机,并且只是简单地回复其自己的MAC地址。
  8. 源主机将IP-MAC地址对添加到ARP缓存中,并可以继续进行。

NOTE Remember that ARP only applies to machines on local subnets (refer to 9.4 Routes and the Kernel Routing Table to see your local subnets). To reach destinations outside your subnet, your host sends the packet to the router, and it’s someone else’s problem after that. Of course, your host still needs to know the MAC address for the router, and it can use ARP to find it.

注意,ARP仅适用于本地子网上的机器(请参考9.4节的路由和内核路由表以查看您的本地子网)。

要想到达子网外的目的地,您的主机将数据包发送到路由器,之后就成为其他人的问题了。

当然,您的主机仍然需要知道路由器的MAC地址,并且可以使用ARP来找到它。

The only real problem you can have with ARP is that your system’s cache can get out-of-date if you’re moving an IP address from one network interface card to another because the cards have different MAC addresses (for example, when testing a machine). Unix systems invalidate ARP cache entries if there’s no activity after a while, so there shouldn’t be any trouble other than a small delay for invalidated data, but you can delete an ARP cache entry immediately with this command:

ARP唯一真正的问题是,如果您将IP地址从一个网络接口卡移动到另一个网络接口卡(例如在测试机器时),系统的缓存可能会变得过时。

Unix系统在一段时间后如果没有活动,将使ARP缓存条目无效,因此除了对无效数据的小延迟之外,不应该有任何问题。

但是,您可以立即使用以下命令删除ARP缓存条目:

# arp -d host

You can also view the ARP cache for a single network interface with

您还可以通过以下命令查看单个网络接口的 ARP 缓存

$ arp -i interface

The arp(8) manual page explains how to manually set ARP cache entries, but you shouldn’t need to do this.

arp(8) 手册页面解释了如何手动设置 ARP 缓存项,但您应该不需要这样做。

NOTE Don’t confuse ARP with Reverse Address Resolution Protocol (RARP). RARP transforms a MAC address back to a hostname or IP address. Before DHCP became popular, some diskless workstations and other devices used RARP to get their configuration, but RARP is rare today.

注意 不要混淆 ARP 与反向地址解析协议(RARP)。

RARP 将 MAC 地址转换回主机名或 IP 地址。

在 DHCP 流行之前,一些无盘工作站和其他设备使用 RARP 获取配置,但现在 RARP 已经很少见了。

9.23 Wireless Ethernet(无线以太网)

In principle, wireless Ethernet (“WiFi”) networks aren’t much different from wired networks. Much like any wired hardware, they have MAC addresses and use Ethernet frames to transmit and receive data, and as a result the Linux kernel can talk to a wireless network interface much as it would a wired network interface. Everything at the network layer and above is the same; the main differences are additional components in the physical layer such as frequencies, network IDs, security, and so on.

原则上,无线以太网(“WiFi”)网络与有线网络并没有太大的区别。

就像任何有线硬件一样,它们具有MAC地址,并使用以太网帧来传输和接收数据,因此Linux内核可以像对待有线网络接口一样与无线网络接口进行通信。

在网络层及以上的所有内容都是相同的;主要的区别在于物理层中有额外的组件,如频率、网络ID、安全等等。

Unlike wired network hardware, which is very good at automatically adjusting to nuances in the physical setup without much fuss, wireless network configuration is much more open-ended. To get a wireless interface working properly, Linux needs additional configuration tools

与有线网络硬件不同,它非常擅长在物理设置中自动调整而不需要太多麻烦,无线网络配置则更加开放。

为了使无线接口正常工作,Linux需要额外的配置工具。

Let’s take a quick look at the additional components of wireless networks.

让我们快速了解一下无线网络的额外组件。

o Transmission details. These are physical characteristics, such as the radio frequency.
o Network identification. Because more than one wireless network can share the same basic medium, you have to be able to distinguish between them. The SSID (Service Set Identifier, also known as the “network name”) is the wireless network identifier.
o Management. Although it’s possible to configure wireless networking to have hosts talk directly to each other, most wireless networks are managed by one or more access points that all traffic goes through. Access points often bridge a wireless network with a wired network, making both appear as one single network.
o Authentication. You may want to restrict access to a wireless network. To do so, you can configure access points to require a password or other authentication key before they’ll even talk to a client.
o Encryption. In addition to restricting the initial access to a wireless network, you normally want to encrypt all traffic that goes out across radio waves.

o 传输细节。这些是物理特性,如无线电频率。
o 网络标识。因为多个无线网络可以共享同一个基本介质,所以你必须能够区分它们。SSID(服务集标识符,也称为“网络名称”)是无线网络的标识符。
o 管理。虽然可以将无线网络配置为主机直接互相通信,但大多数无线网络由一个或多个访问点管理,所有流量都通过这些访问点。访问点通常将无线网络与有线网络桥接起来,使其看起来像一个单一的网络。
o 认证。您可能希望限制对无线网络的访问。为此,您可以配置访问点要求客户端在进行通信之前输入密码或其他认证密钥。
o 加密。除了限制对无线网络的初始访问之外,通常还希望对通过无线电波传输的所有流量进行加密。

The Linux configuration and utilities that handle these components are spread out over a number of areas. Some are in the kernel: Linux features a set of wireless extensions that standardize user-space access to hardware. As far as user space goes, wireless configuration can get complicated, so most people prefer to use GUI frontends, such as the desktop applet for NetworkManager, to get things working. Still, it’s worth looking at a few of the things happening behind the scenes.

处理这些组件的Linux配置和实用程序分散在多个领域。

其中一些在内核中:Linux提供了一组无线扩展,用于标准化用户空间对硬件的访问。

就用户空间而言,无线配置可能会变得复杂,因此大多数人更喜欢使用GUI前端,例如NetworkManager的桌面小程序,来使事情正常运行。

不过,了解一下幕后发生的一些事情仍然是值得的。

9.23.1 iw

You can view and change kernel space device and network configuration with a utility called iw. To use iw, you normally need to know the network interface name for the device, such as wlan0. Here’s an example that dumps a scan of available wireless networks. (Expect a lot of output if you’re in an urban area.)

您可以使用一个名为iw的实用工具来查看和更改内核空间设备和网络配置。

要使用iw,通常需要知道设备的网络接口名称,例如wlan0。

以下是一个示例,显示可用无线网络的扫描结果(如果您在城市地区,可能会有大量输出)。

# iw dev wlan0 scan

NOTE The network interface must be up for this command to work (if it’s not, run ifconfig wlan0 up), but you don’t need to configure any network layer parameters, such as an IP address.

注意:要使该命令生效,网络接口必须处于启动状态(如果没有启动,运行ifconfig wlan0 up),但您不需要配置任何网络层参数,例如IP地址。

If the network interface has joined a wireless network, you can view the network details like this:

如果网络接口已连接到无线网络,您可以像这样查看网络详细信息:

# iw dev wlan0 link

The MAC address in the output of this command is from the access point that you’re currently talking to.

该命令输出中的MAC地址是您当前正在通信的接入点的地址。

NOTE The iw command distinguishes between physical device names such as phy0 and network interface names such as wlan0 and allows you to change various settings for each. You can even create more than one network interface for a single physical device. However, in nearly all basic cases, you’ll just use the network interface name.

注意:iw命令区分物理设备名称(如phy0)和网络接口名称(如wlan0),并允许您为每个名称更改各种设置。您甚至可以为单个物理设备创建多个网络接口。

但是,在几乎所有基本情况下,您只需使用网络接口名称即可。

Use iw to connect a network interface to an unsecured wireless network as follows:

使用iw将网络接口连接到一个未加密的无线网络,可以按照以下步骤进行:

# iw wlan0 connect network_name

Connecting to secured networks is a different story. For the rather insecure Wired Equivalent Privacy (WEP) system, you can use the keys parameter with the iw connect command. However, you shouldn’t use WEP if you’re serious about security

连接到受保护的网络则是另一回事。

对于相当不安全的Wired Equivalent Privacy(WEP)系统,您可以使用iw connect命令的keys参数。

然而,如果您对安全性比较重视,不应使用WEP。

9.23.2 Wireless Security(无线安全)

For most wireless security setups, Linux relies on a daemon called wpa_supplicant to manage both authentication and encryption for a wireless network interface. This daemon can handle both WPA (WiFi Protected Access) and WPA2 schemes of authentication, as well as nearly any kind of encryption technique used on wireless networks. When the daemon first starts, it reads a configuration file (by default, /etc/wpa_supplicant.conf) and attempts to identify itself to an access point and establish communication based on a given network name. The system is well documented; in particular, the wpa_supplicant(1) and wpa_supplicant.conf(5) manual pages are very detailed.

对于大多数无线安全设置,Linux依赖一个名为wpa_supplicant的守护进程来管理无线网络接口的身份验证和加密。

该守护进程可以处理WPA(WiFi Protected Access)和WPA2身份验证方案,以及几乎所有在无线网络上使用的加密技术。

当守护进程首次启动时,它会读取一个配置文件(默认为/etc/wpa_supplicant.conf),并尝试根据给定的网络名称向访问点标识自己并建立通信。

该系统有很好的文档支持,特别是wpa_supplicant(1)和wpa_supplicant.conf(5)手册非常详细。

Running the daemon by hand every time you want to establish a connection is a lot of work. In fact, just creating the configuration file is tedious due to the number of possible options. To make matters worse, all of the work of running iw and wpa_supplicant simply allows your system to join a wireless physical network; it doesn’t even set up the network layer. And that’s where automatic network configuration managers such as NetworkManager take a lot of pain out of the process. Although they don’t do any of the work on their own, they know the correct sequence and required configuration for each step toward getting a wireless network operational.

每次想要建立连接时手动运行守护进程是很麻烦的工作。

事实上,由于可能的选项数量,仅创建配置文件就很繁琐。更糟糕的是,运行iw和wpa_supplicant的所有工作只是让您的系统加入一个无线物理网络,甚至没有设置网络层。

而这正是自动网络配置管理器(如NetworkManager)在这个过程中承担了很多痛苦的地方。

虽然它们自己不做任何工作,但它们知道每个步骤的正确顺序和所需配置,以使无线网络正常运行。

9.24 Summary(摘要)

You can now see that understanding the positions and roles of the various network layers is critical to understanding how Linux networking operates and how to perform network configuration. Although we’ve covered only the basics, more advanced topics in the physical, network, and transport layers bear similarities to what you’ve seen. Layers themselves are often subdivided, as you just saw with the various pieces of the physical layer in a wireless network.

现在您可以看到,了解各个网络层的位置和角色对于理解Linux网络操作和执行网络配置至关重要。

虽然我们只涵盖了基础知识,但物理层、网络层和传输层的更高级主题与您所见到的内容有相似之处。

层本身通常会细分,就像您刚才在无线网络的物理层中看到的各个部分一样。

A substantial amount of action that you’ve seen in this chapter happens in the kernel, with some basic userspace control utilities to manipulate the kernel’s internal data structures (such as routing tables). This is the traditional way of working with the network. However, as with many of the topics discussed in this book, some tasks aren’t suitable for the kernel due to their complexity and need for flexibility, and that’s where userspace utilities take over. In particular, NetworkManager monitors and queries the kernel and then manipulates the kernel configuration. Another example is support for dynamic routing protocols such as Border Gateway Protocol (BGP), which is used in large Internet routers.

在本章中,您所见到的大部分操作都发生在内核中,使用一些基本的用户空间控制实用程序来操作内核的内部数据结构(如路由表)。

这是与网络一起工作的传统方式。

然而,与本书讨论的许多主题一样,由于其复杂性和灵活性的需求,一些任务并不适合在内核中进行,这就是用户空间实用程序接管的地方。

特别是,NetworkManager监视和查询内核,然后操作内核配置。

另一个例子是对动态路由协议(如边界网关协议BGP)的支持,它在大型互联网路由器中使用。

But you’re probably a little bit bored with network configuration by now. Let’s turn to using the network— the application layer.

但是您可能对网络配置有点厌倦了。让我们转向使用网络——应用层。


Xander
198 声望51 粉丝