# Something about IPv4

## 前言

虽然`IP v6`是未来的主流，但目前学校以及大量我国单位还在用旧的`v4`

## 什么是`IP`

Internet Protocol

其用十进制表示，看起来像这样：`192.168.1.1` （就是4段`0~255`的数）

用2进制表示，是这样：`11111111.11111111.111111111.00000000` = `255.255.255.0`

平时写代码的时候，只是操作单个主机、单个IP。

一旦把管理范围扩大，我们就需要管理整个网络了，所以真实世界的IP不是孤立存在的，而是成群结队的出现。

比如一个范围由`192.168.0.0`到`192.168.255.255`的网络

1. 这个网络的第一个IP地址， `192.168.0.0`，被当成这个网络的标识
2. 该网络的最后一个地址，`192.168.255.255`，会被当成广播地址，向它发信息，那条信息会被广播到该网络的每一个地址

由此一来，IP必须由两部分组成：网络号+主机号

举个例子：在网络`202.93.0.0`里，某个IP`202.93.44.55`的主机号是`44.55`，网络号是`202.93`

## 地址要分类

人们最开始把所有`IP v4`地址像这样分(假设`网络号=c`，`主机号=x`)：

```
Class      Theoretical Address Range
A      0.0.0.0 to 127.255.255.255      c.x.x.x
B      128.0.0.0 to 191.255.255.255      c.c.x.x
C      192.0.0.0 to 223.255.255.255      c.c.c.x
D      224.0.0.0 to 239.255.255.255      I don't know
```

`IPv4`总数是`2的32次方`=`4,294,967,296`，不够用

所以`聪明的人类`又开始`动歪脑筋`折磨后人了(但事实上只需要写一个程序自动帮我们计算，只是不知道为什么学校要求学生手动计算这个东西，真麻烦)

具体的原理可以参照 `Data Communications and Networking - Behrouz A. Forouzan` 这本书

我这里只讲一讲应试教育的解题方法(其实我压根就不该写这么多，直接写题目才是正确的套路)

题目：将一个 B类 的网络`172.17.0.0`划分为14个子网，求每个子网的子网掩码 and 每个子网的IP范围

### (1)

因为 是B类网，所以 `122.17`固定不变，`0.0`可变； `0.0`变为 2进制 为`00000000.00000000`

因为要划分为 14 个子网，我们需要思考`2的多少次方刚好` > 14

$$2^3=8$$ ，$$2^4=16$$

因为 $$2^4=16$$ 刚好大于 14，所以我们要占用`主机位2进制`前4位来划分子网

因为`子网掩码`本质上是用 1 代表 `网络位`，0代表`主机位`

所以该题的子网掩码的2进制形式变为了 `11111111.11111111.11110000.00000000`

把它变成10进制: 8个1为255，8个0为0

`11110000`的转换方法：

$$
\begin{align\*}
&0 \times 2^0 + 0 \times 2^1 + 0 \times 2^2 + 0 \times 2^3 + 1 \times 2^4 + 1 \times 2^5 + 1 \times 2^6 + 1 \times 2^7
\ \\
&= 0 + 0 + 0 + 0 + 16 + 32 + 64 + 128
\ \\
&= 0 + 48 + 64 + 128
\ \\
&= 112 + 128
\ \\
&= 240
\end{align\*}
$$

所以最终`该题子网掩码`变为了 `255.255.240.0`

### (2)

不知道原因，但我从我课本的描述中总结出了地址划分的规律

假设`主机位被占用的`个数为 $$x$$，$$B = 8 - x$$ ，$$2^B - 1$$ 为每个子网的范围

在这道题，主机位被占用的个数为 4，$$B=8-4=4$$

$$2^4 - 1 = 16 - 1 = 15$$ ，得到了每个子网的范围后，就可以开始写表了

```
初始地址为 172.17.0.1

172.17.0.1 ~ 172.17.15.254
172.17.16.1 ~ 172.17.31.254
172.17.32.1 ~ 172.17.47.254
... ...
172.17.224.1 ~ 172.17.239.254
172.17.240.1 ~ 172.17.255.254
```

不要问我 首和尾 哪儿去了，一个用于标识网络，一个用于广播

## 后续

至于更多的题，我暂时不想写了


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yingshaoxo.gitbook.io/university-notes/data-communications-and-networking/something-about-ipv4.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
