跳至主要内容

对网关的理解

网络模型被OSI分成七层,TCP/IP协议大致对应了2、3、4、7层,分别是数据链路层、网络层、传输层、应用层,IP协议处于网络层上,它的工作原理说白了并不复杂:
  1. 整个互联网上所有的机器都有唯一一个IP地址对应。这并没有什么稀奇的,MAC地址也是唯一的,稀奇的在后面
  2. 机器的IP地址按照连接顺序进行了一定程度的分组,这样一个连续的IP段大致都在相同的路线上,这样路由器寻找特定IP地址的时候就方便多了,把整个地址空间分成若干个可能重叠的大段,每个大段一般这样表示:A.B.C.D/n,表示32位IP地址的前n位与A.B.C.D的前n位相同。比如192.168.1.0/24,所有前24位与192.168.1.0相同的都是这个网段的IP,由于IP地址8位一分组,24位就是前三段,也就是192.168.1.x。符合规范的这段连续的IP段就叫做一个子网。这种子网的表示方法叫做CIDR。
  3. 这种表示方法对人来说比较直观,但是计算机有另一种更快速的计算方法,对于A.B.C.D/n,我们构造一个前n位都是1、后面其他位都是0的IP地址,这个32位IP地址和A.B.C.D按位与的结果,就是前n位与A.B.C.D相同而后面其他位都是0的IP地址;如果这个32位IP地址和另一个IP地址与的结果,刚好与A.B.C.D与的结果相等,就说明这个IP地址和A.B.C.D的前n位相等,就说明新IP地址在CIDR范围内。我们把前n位都是1、后面其他位是0的地址也用IP地址的形式表示出来,那么192.168.1.0/24对应的就是255.255.255.0,这个就叫做子网掩码,掩码也就是mask,mask在计算机用语当中表示按位与的操作数,用来从目标数中取出特定的二进制位。也就是说IP+子网掩码是CIDR的另一种表示形式。

对于任意一台计算机或者路由器来说,它首先会有一些本地的链路,这些链路的IP地址都在各自特定的CIDR当中,这个子网叫做链路子网,链路子网中的IP地址都可以通过链路层协议直接访问,具体的访问方法与IP协议无关,在以太网当中是靠ARP,但是如果是WLAN,或者令牌环网,或者PPPoE,又会有所不同。比如子网是192.168.1.0/24,那么范围内所有IP地址都会直接调用链路层协议访问。表现在路由表中,就是这样一项:
192.168.1.0/24 -> link local, ifindex = XXX
即“192.168.1.0/24范围的IP通过XXX网卡的链路层协议直接访问”
如果还有其他链路,也会有相应的表项,比如说还有一个网卡上面的链路子网是111.222.1.0/24,那么就有另一项:
111.222.1.0/24 -> link local, ifindex = YYY
特别的,每个网卡上都会有一个IP地址,是本机的IP地址。当数据包发到这个IP地址的时候,设备就会正确理解“这个数据包是发给我自己的”,否则会理解为“这个数据包需要我代为转发”。这些本机的IP地址一定在链路层子网当中,比如说192.168.1.0/24中本机的IP地址是192.168.1.1,111.222.1.0/24中的IP地址是111.222.1.15,那么就有两个表项:
192.168.1.1/32 -> local
111.222.1.15/32 -> local
到local表示交给本机的更高层的协议栈,比如TCP/UDP去处理。否则会转发到其他机器。
我们注意到这些表项和刚才的表项有重叠的部分,比如说192.168.1.1/32其实包含在192.168.1.0/24里面。路由表的不同表项有不同的优先级,子网越小的越优先,也就是后面n越大的越优先,这样192.168.1.1/32就比192.168.1.0/24优先。

除了这些IP地址以外,其他的IP地址显然是无法直接访问的,需要由其他设备进行转发。不同网段的IP地址可能需要不同的设备进行转发。我们必须在路由表当中记住某段IP具体由哪个设备转发,记录的方法是记住需要转发的IP段CIDR,和需要发往的设备的IP地址,像这样:
100.101.1.0/24 -> via 192.168.1.17
这个via后面的地址,192.168.1.17,这个设备有进一步将数据包转发到目的网段的能力,比如说上面有一个链路层子网就是100.101.1.0/24,或者有另一条路由信息表明这个网段应该进一步发给其他的某个设备。这个设备在IP协议当中就叫做Gateway(网关),因为所有发到目的网段的流量都会从这个设备上经过,这个设备像个门一样,把两个网段连接了起来。
大多数情况下,这个IP地址位于某个链路层子网中,这样本机可以直接通过链路层协议将IP报文发送到网关。一部分设备(主要是硬件路由器)支持递归的路由表配置,这个时候网关地址可以不是本地链路层子网中的地址,当需要将IP报文发送到这个网关时,设备会递归查找网关的路由信息,直到查找到可以直接发送的地址为止。

互联网上的网段太多了,而且天天都在变,我们不可能给每个设备都配上互联网上所有的网段。幸好,对于大部分设备来说,除了特定的少数几个网段以外,大部分IP地址都有相同的网关,于是我们可以通过配置一个包含整个IP空间的CIDR来指定大部分IP地址的共同的网关:
0.0.0.0/0 -> via 111.222.1.254
由于前面说的原则,子网越小越优先,这条规则的优先度最低,而且能匹配所有的IP地址,因此可以理解为无法匹配到其他子网网段时使用的默认规则,因此这个网关一般叫做默认网关。
一个设备可能有多个网关,但是一般最多只有一个默认网关(不考虑等价路由、策略路由等复杂的情况)。也有可能没有默认网关,比如说骨干网上的路由器通过BGP协议交换路由信息,一般路由表就由非常多的CIDR组成,这些CIDR合起来能覆盖互联网上所有的公网IP。

最后说下链路层地址与IP地址。许多链路层协议也有自己的地址,一般是MAC地址,比如最常用的以太网。链路层地址在链路层协议中使用,表明这个链路层报文会被发给谁;而IP地址在IP层协议中使用,表明这个报文最终要发给谁。可以分为两种情况:
1. 直接通过链路层发送:
链路层地址: (源MAC地址) (目的MAC地址)
IP地址: (源IP地址) (目的IP地址)
2. 经过网关转发
从本机出发发往网关时,链路层的目的是网关而IP层的目的不是网关:
链路层地址: (本机源MAC地址) (网关MAC地址)
IP地址: (本机IP地址) (目的IP地址)
网关转发到其他网关:
链路层地址: (网关MAC地址) (下一跳网关MAC地址)
IP地址: (本机IP地址) (目的IP地址)
最后一个网关转发到目标:
链路层地址: (最后一个网关MAC地址) (目的MAC地址)
IP地址: (本机IP地址) (目的IP地址)
在转发过程中,IP报文的源和目的保持不变,链路层地址则只和这一跳的双方有关,甚至如果中间经过了不一样的链路层,还会更换二层数据包的格式。

Popular posts from 产品随想的博客

Interview at the All Things Digital D5 Conference, Steve and Bill Gates spoke with journalists Kara Swisher and Walt Mossberg onstage in May 2007.

Kara Swisher: The first question I was interested in asking is what you think each has contributed to the computer and technology industry— starting with you, Steve, for Bill, and vice versa. Steve Jobs: Well, Bill built the first software company in the industry. And I think he built the first software company before anybody really in our industry knew what a software company was, except for these guys. And that was huge. That was really huge. And the business model that they ended up pursuing turned out to be the one that worked really well for the industry. I think the biggest thing was, Bill was really focused on software before almost anybody else had a clue that it was really the software that— KS: Was important? SJ: That’s what I see. I mean, a lot of other things you could say, but that’s the high-order bit. And I think building a company’s really hard, and it requires your greatest persuasive abilities to hire the best ...

Commencement Address at Stanford University--“Stay hungry. Stay foolish.”

I am honored to be with you today for your commencement from one of the finest universities in the world. Truth be told— I never graduated from college. This is the closest I’ve ever gotten to a college graduation. Today I want to tell you three stories from my life. That’s it. No big deal. Just three stories. The first story is about connecting the dots. I dropped out of Reed College after the first six months but then stayed around as a drop-in for another eighteen months or so before I really quit. So why did I drop out? It started before I was born. My biological mother was a young, unwed graduate student, and she decided to put me up for adoption. She felt very strongly that I should be adopted by college graduates, so everything was all set for me to be adopted at birth by a lawyer and his wife. Except that when I popped out they decided at the last minute that they really wanted a girl. So my parents, who were on a waiting...

产品随想 | 周刊 第43期:历史上的今天

Products Huberman Lab   https://hubermanlab.com/ 一款聚焦于健康的播客 今日热榜   https://tophub.today/ 聚合展示,国内各热门榜单,对跟进热点非常有帮助,热点运营的好帮手 SketchyBar   https://github.com/FelixKratz/SketchyBar A highly customizable macOS status bar replacement Mac菜单栏定制 自定义程度很高,看作者展示的案例,暂时没想出这样的好处(不过应用本身的编辑,确实也没啥意义)生命在于折腾吧! Thanks-Mirror   https://github.com/eryajf/Thanks-Mirror 整理记录各个包管理器,系统镜像,以及常用软件的好用镜像,Thanks Mirror。 Musicn   https://github.com/zonemeen/musicn 一个下载高品质音乐的命令行工具,音乐来源: 咪咕 Planet Minecraft A creative Minecraft community fansite sharing maps, minecraft skins, resource packs, servers, mods, and more. 里面有很多动人的故事 可能是世界上最大的Minecraft社区,从2010年至今 The Uncensored Library   https://www.uncensoredlibrary.com/en blockworks   https://www.blockworks.uk/ "Distinctive maps for Minecraft that have educated players and risen to the level of art" 游戏也可以让人有更高的实现,而不仅仅是沉迷其中,国外游戏厂商比我们做的好太多 Minecraft_Memory_Bypass_GUI   https://github.com/xingchuanzhen/Minecraft_Memory_Bypass_GUI 绕过Minecraft...

巴菲特致股东信-1976年

 笔记: 为什么选择轻资产行业:当竞争疯狂时,不会强迫加入降价大战 最终选择了费雪的思想,选择能理解的优秀企业,以合理的价格买入并长期拥有 翻译: 雪球:https://xueqiu.com/6217262310/131440258 备份:https://archive.ph/XLK0S 原文: To the Stockholders of Berkshire Hathaway Inc, After two dismal years, operating results in 1976 improved significantly. Last year we said the degree of progress in insurance underwriting would determine whether our gain in earnings would be "moderate" or "major." As it turned out, earnings exceeded even the high end of our expectations. In large part, this was due to the outstanding efforts of Phil Liesche's managerial group at National Indemnity Company. In dollar terms, operating earnings came to $16,073,000, or $16.47 per share. While this is a record figure, we consider return on shareholders' equity to be a much more significant yardstick of economic performance. Here our result was 17.3%, moderately above our long-term average and even further above the average o...

巴菲特致股东信-1973年

 笔记: 在上一年度预测的今年竞争加剧导致利润下滑,真的发生了 翻译Link: 雪球:https://xueqiu.com/6217262310/131257618 备份:https://archive.ph/KIfdT 原文: To the Stockholders of Berkshire Hathaway Inc.: Our financial results for 1973 were satisfactory, with operating earnings of $11,930,592, producing a return of 17.4% on beginning stockholders' equity. Although operating earnings improved from $11.43 to $12.18 per share, earnings on equity decreased from the 19.8% of 1972. This decline occurred because the gain in earnings was not commensurate with the increase in shareholders' investment. We had forecast in last year's report that such a decline was likely. Unfortunately, our forecast proved to be correct. Our textile, banking, and most insurance operations had good years, but certain segments of the insurance business turned in poor results. Overall, our insurance business continues to be a most attractive area in which to employ capital. Management'...

巴菲特致股东信-1975年

 笔记: 华盛顿邮报已成为伯克希尔第一重仓股 翻译: 雪球:https://xueqiu.com/6217262310/131409324 备份:https://archive.ph/4hgK3 原文: To the Stockholders of Berkshire Hathaway Inc.: Last year, when discussing the prospects for 1975, we stated “the outlook for 1975 is not encouraging.” This forecast proved to be distressingly accurate. Our operating earnings for 1975 were $6,713,592, or $6.85 per share, producing a return on beginning shareholders ’ equity of 7.6%. This is the lowest return on equity experienced since 1967. Furthermore, as explained later in this letter, a large segment of these earnings resulted from Federal income tax refunds which will not be available to assist performance in 1976. On balance, however, current trends indicate a somewhat brighter 1976. Operations and prospects will be discussed in greater detail below, under specific industry titles. Our expectation is that significantly better results in textiles, earnings added from recent acquisitio...

Steve Jobs introduced the iPhone on January 9, 2007.

This is a day I’ve been looking forward to for two and a half years. Link Every once in a while, a revolutionary product comes along that changes everything. And Apple has been— well, first of all, one’s very fortunate if you get to work on just one of these in your career. Apple’s been very fortunate. It’s been able to introduce a few of these into the world. In 1984, we introduced the Macintosh. It didn’t just change Apple, it changed the whole computer industry. In 2001, we introduced the first iPod, and it didn’t just change the way we all listen to music, it changed the entire music industry. Well, today, we’re introducing three revolutionary products of this class. The first one is a widescreen iPod with touch controls. The second is a revolutionary mobile phone. And the third is a breakthrough internet communications device. So, three things: a widescreen iPod with touch controls; a revolutionary mobile phone; and a breakthrough internet communicat...

产品随想 | 周刊 第90期:史家之绝唱,无韵之离骚

Why AI Will Save the World   https://a16z.com/2023/06/06/ai-will-save-the-world/ Marc Andreessen的雄文,十分有說服力,邏輯清晰 辯證了現今AI監管拋出的5個可能的AI問題 讀的過程中,腦海裏浮現的都是編程隨想那篇文章 为什么马克思是错的?——全面批判马列主义的知名著作导读   https://program-think.blogspot.com/2018/09/Book-Review-The-Errors-of-Marxism-Leninism.html 兩者的思維鏈條、敘事方式,非常相似 人民聖殿教   https://zh.wikipedia.org/zh-hk/人民圣殿教?useskin=vector 瓊斯自稱是神的化身,幾千年前轉世為釋迦牟尼,創建了佛教;後來又轉世為耶穌基督,創建了基督教;之後短期化身轉世為巴孛,建立巴哈伊信仰;最後轉世為列寧,將社會主義發揚光大。 邪教徒聲稱自己轉世成了列寧,這說明了什麼? Apple Vision   https://stratechery.com/2023/apple-vision Omnivore   https://github.com/omnivore-app/omnivore Omnivore is a complete, open source read-it-later solution for people who like reading. How the YouTube Algorithm Works in 2023: The Complete Guide   https://blog.hootsuite.com/how-the-youtube-algorithm-works/#A_brief_history_of_the_YouTube_algorithm 外人眼中的YouTube推薦算法變遷 Histography   https://histography.io/ “Histography" is interactive timeline that spans across 14 billion years of history, f...

巴菲特致股东信-1974年

 笔记: 价格战企业的逻辑:需要降价获取销量--->需要降低成本--->怎么降?扩大规模以摊低成本--->提高固定资产投入--->净资产回报率会降低 翻译: 雪球:https://xueqiu.com/6217262310/131257947 备份:https://archive.ph/5CEP6 原文: To the Stockholders of Berkshire Hathaway Inc.: Operating results for 1974 overall were unsatisfactory due to the poor performance of our insurance business. In last year's annual report some decline in profitability was predicted but the extent of this decline, which accelerated during the year, was a surprise. Operating earnings for 1974 were $8,383,576, or $8.56 per share, for a return on beginning shareholders' equity of 10.3%. This is the lowest return on equity realized since 1970. Our textile division and our bank both performed very well, turning in improved results against the already good figures of 1973. However, insurance underwriting, which has been mentioned in the last several annual reports as running at levels of unsustainable profitability, turned dramatically worse...

Interview with Steve Jobs, WGBH, 1990

Interviewer: what is it about this machine? Why is this machine so interesting? Why has it been so influential? Jobs: Ah ahm, I'll give you my point of view on it. I remember reading a magazine article a long time ago ah when I was ah twelve years ago maybe, in I think it was Scientific American . I'm not sure. And the article ahm proposed to measure the efficiency of locomotion for ah lots of species on planet earth to see which species was the most efficient at getting from point A to point B. Ah and they measured the kilocalories that each one expended. So ah they ranked them all and I remember that ahm...ah the Condor, Condor was the most efficient at [CLEARS THROAT] getting from point A to point B. And humankind, the crown of creation came in with a rather unimpressive showing about a third of the way down...