我正在研究标准的 ping 实现。这里创建了icmp结构,并填充了数据。IP层是内核添加的。但是,当我们使用函数 http://linux.die.net/man/2/recvfrom 收到消息时我观察到他们是先解析IP包,再解析ICMp包。为什么会这样。我所引用的代码是在线提供的标准 ping 实现。
最佳答案
这是因为在原始套接字上接收 IPv4 数据包时始终包含 header 。请注意 raw(7)
中的以下内容(强调我的):
The IPv4 layer generates an IP header when sending a packet unless the
IP_HDRINCL
socket option is enabled on the socket. When it is enabled, the packet must contain an IP header. For receiving the IP header is always included in the packet.
由于始终包含 header 并且 has variable length (对于 IPv4),必须对其进行解析以找出 ICMP 数据的起始位置。
至于为什么 标题没有被删除(很抱歉,如果这是您唯一想知道的事情),我不知道。我的疯狂猜测是,处理原始 IPv4 的足够多的程序想要查看 header ,似乎不值得将剥离它作为一个选项。快速浏览一下,标题似乎已针对 IPv6 进行了剥离。
顺便说一句,标准的ping
和ping6
来自iputils,其中ping_common.c,ping.c 和 ping6.c 是最相关的源文件。
关于c - 为什么在ping程序中内核没有去掉IP层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29048410/