動態

詳情 返回 返回

【Linux】《how linux work》第九章 瞭解網絡及其配置 - 動態 詳情

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.

但是您可能對網絡配置有點厭倦了。讓我們轉向使用網絡——應用層。

user avatar dengjijie 頭像 xiaoxiansheng_5e75673e1ae30 頭像 tangbo_5f9242f233a7e 頭像
點贊 3 用戶, 點贊了這篇動態!
點贊

Add a new 評論

Some HTML is okay.