IP头部结构如下
Version – the version of the IP protocol. For IPv4, this field has a value of 4.
Header length – the length of the header in 32-bit words. The minumum value is 20 bytes, and the maximum value is 60 bytes.
Priority and Type of Service – specifies how the datagram should be handled. The first 3 bits are the priority bits.
Total length – the length of the entire packet (header + data). The minimum length is 20 bytes, and the maximum is 65,535 bytes.
Identification – used to differentiate fragmented packets from different datagrams.
Flags – used to control or identify fragments.
Fragmented offset – used for fragmentation and reassembly if the packet is too large to put in a frame.
Time to live – limits a datagram’s lifetime. If the packet doesn’t get to its destination before the TTL expires, it is discarded.
Protocol – defines the protocol used in the data portion of the IP datagram. For example, TCP is represented by the number 6 and UDP by 17.
Header checksum – used for error-checking of the header. If a packet arrives at a router and the router calculates a different checksum than the one specified in this field, the packet will be discarded.
Source IP address – the IP address of the host that sent the packet.
Destination IP address – the IP address of the host that should receive the packet.
Options – used for network testing, debugging, security, and more. This field is usually empty.
当网络包转交到协议栈(TCP/IP)时,IP模块会首先开始工作,检查IP头部,IP模块首先会检查IP头部的格式是否符合规范,然后检查接收方IP地址,看包是不是发给自己的。当服务器启用类似路由器的包转发功能时,对于不是发给自己的包,会像路由器一样根据路由表对包进行转发。
确认包是发给自己的之后,接下来需要检查包有没有被分片检查IP头部的内容就可以知道是否分片,如果是分片的包,则将包暂时存放在内存中,等所有分片全部到达之后将分片组装起来还原成原始包;如果没有分片,则直接保留接收时的样子,不需要进行重组。到这里,我们就完成了包的接收。
接下来需要检查IP头部的协议号字段,并将包转交给相应的模块。例如,如果协议号为06(十六进制),则将包转交给TCP模块;如果是11(十六进制),则转交给UDP模块。这里我们假设这个包被交给TCP模块处理,然后继续往下看。
协议栈的IP模块会检查IP头部,
(1)判断是不是发给自己的;
(2)判断网络包是否经过分片;
(3)将包转交给TCP模块或UDP模块。
总结
- IP模块干如上三件事
- IP头部的信息决定了能干点啥