IPv4之接收数据包流程


IPv4之协议族初始化中有介绍,IPv4协议会向设备接口层注册接收处理函数,使得ETH_P_IP类型的数据包将会交由ip_rcv()函数处理。这篇笔记就从该函数入手,一直到将数据包递交给更高层协议为止,从宏观角度分析下数据包在IP层的传递过程。

主要涉及如下文件:

源代码路径 说明
net/ipv4/ip_input.c IP协议输入报文处理过程
net/ipv4/ip_forward.c IP协议转发报文处理过程

接收报文入口: ip_rcv()

我们知道,设备接口层最后会在netif_receive_skb()函数中,根据skb->protocol字段查表,将skb递交给更高层的协议处理,对于IPv4来讲,其注册的接收函数就是ip_rcv():

@skb: 数据包
@dev:数据包的当前输入网络设备(层二可能会使用一些聚合技术)
@pt:数据包的类型
@orig_dev: 接收数据包的原始网络设备
int ip_rcv(struct sk_buff *skb, struct net_device *dev,
	struct packet_type *pt, struct net_device *orig_dev)
{
   
	struct iphdr *iph;
	u32 len;

	if (dev->nd_net != &init_net)
		goto drop;

	/* When the interface is in promisc. mode, drop all the crap
	 * that it receives, do not try to analyse it.
	 */
    // 在混杂模式下,发往其它主机的一些数据包有可能会到达这里,IPv4并不关注这种包,忽略它们
	if (skb->pkt_type == PACKET_OTHERHOST)
		goto drop;
	IP_INC_STATS_BH(IPSTATS_MIB_INRECEIVES);

	// 因为后面需要修改skb的内容,所以如果skb是被共享的,那么需要克隆一个新的
	if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL) {
   
		IP_INC_STATS_BH(IPSTATS_MIB_INDISCARDS);
		goto out;
	}
	// 确保skb数据区中至少有IP首部长度个字节的数据,如果不满足,该函数会从frags数组中拷贝
	if (!pskb_may_pull(skb, sizeof(struct iphdr)))
		goto inhdr_error;
	// pskb_may_pull()可能会调整内存,所以需要重新计算iph
	iph = ip_hdr(skb);

	/*
	 *	RFC1122: 3.1.2.2 MUST silently discard any IP frame that fails the checksum.
	 *
	 *	Is the datagram acceptable?
	 *
	 *	1.	Length at least the size of an ip header
	 *	2.	Version of 4
	 *	3.	Checksums correctly. [Speed optimisation for later, skip loopback checksums]
	 *	4.	Doesn't have a bogus length
	 */
	// 1&2:检查首部长度和IP协议版本号
	if (iph->ihl < 5 || iph->version != 4)
		goto inhdr_error;
	// 这里之所以又做一遍,是因为IP首部可能还有选项部分,iph->ihl*4是IP报文的真实首部长度
	if (!pskb_may_pull(skb, iph->ihl*4))
		goto inhdr_error;
	iph = ip_hdr(skb);
	// 检查IP首部的校验和,确保IP报头传输没有问题
	if (unlikely(ip_fast_csum((u8 *)iph, iph->ihl)))
		goto inhdr_error;
	
    // 校验IP数据包的总长度
	len = ntohs(iph->tot_len);
	if (skb->len < len) {
   
		IP_INC_STATS_BH(IPSTATS_MIB_INTRUNCATEDPKTS);
		goto drop;
	} else if (len < (iph->ihl*4))
		goto inhdr_error;

	/* Our transport medium may have padded the buffer out. Now we know it
	 * is IP we can trim to the true length of the frame.
	 * Note this now means skb->len holds ntohs(iph->tot_len).
	 */
    // 如注释所述,层二有可能会在IP数据包上打padding,所这里知道了IP数据包的总长度,
    // 需要对SKB的长度字段进行调整并重新计算L4校验和(因为硬件在校验时是包含了这部分
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值