icmp应答包如何定位ping进程

来源:互联网 发布:外资企业数据 编辑:程序博客网 时间:2024/05/16 11:51

今天一个朋友说他自己实现一个ping程序。要过他的代码看了一看。通常的ping程序都是通过icmp协议实现,但是icmp协议却不同于tcp与udp。tcp与udp协议首部包含着源端口号和目的端口号,所以当一个tcp或udp协议应答返回时,我们可以根据对应的端口号,定位到相应的处理进程。但是icmp的协议里面并不包含端口号,ping程序是如何定位到应答包属于自己发出的呢?

icmp 报文首部

// ICMP header for both IPv4 and IPv6.//// The wire format of an ICMP header is:// // 0               8               16                             31// +---------------+---------------+------------------------------+      ---// |               |               |                              |       ^// |     type      |     code      |          checksum            |       |// |               |               |                              |       |// +---------------+---------------+------------------------------+    8 bytes// |                               |                              |       |// |          identifier           |       sequence number        |       |// |                               |                              |       v// +-------------------------------+------------------------------+      ---

在RFC标准中有这样一段话:

The data received in the echo request message must be returned in the echo reply message.

The identifier and sequence number may be used by the echo sender to aid in matching the replies with the echo requests. For example, the identifier might be used like a port in TCP or UDP to identify a session, and the sequence number might be incremented on each echo request sent. The echoing node returns these same values in the echo reply.

因为请求包首部一定会在应答包中被返回,所以 identifier 可以用来做类似 TCP 或 UDP 里面的端口去区分哪个进程,而 sequence 可以用作序列号去匹配不同的消息。
这样我考虑的问题就解决了。

这里是我找到的 ping 的实现:

http://www.boost.org/doc/libs/1_50_0/doc/html/boost_asio/examples.html#boost_asio.examples.icmp

可以简单修改一下,去验证如果同时开启2个 ping 程序,一个应答包返回后,是否会反馈到这2个程序中。我验证了,确实会。不信的话,你自己来试一试。


0 0
原创粉丝点击