您的位置:首页 > 其它

基于多线程设计检测多台主机ICMP消息串位的问题

2015-01-04 19:25 459 查看
一个进程中需要检测多台主机是否正常工作,采用了ICMP检测的方式,每个主机一个线程,定时PING对应主机是否存活。最后发现当有主机down机的情况下,依然能收到ICMP的回应报文。

这个问题看起来很奇怪,其实了解PING的实现原理就会觉得出现这样的问题很正常。

首先ICMP是基于RAW套接字的,RAW套接字只匹配协议,并不按流匹配,也就是说一个或者多个进程采用RAW方式监听同样协议的socket时,都能收到相同的报文。多个ping进程之所以不出问题,是因为PING将ICMP报文中的icmp_id设置为对应的进程号,进一步通过进程号来区分是否属于自己的报文。最主要的原因是用户态已经去掉了ICMP的报文头,无法看到原地址和目的地址了,所以只能通过ICMP报文的内容来区分。

进而就可以明白为什么多线程情况下检测多台主句会出问题了,因为进程号都一样,所以大家都能收到相同的回应报文,这种情况下只需要修改下icmp协议中icmp_id为自己定义的值就行了。

在TCP和UDP协议情况下,不会用到RAW属性去创建套接字,所以不会有以上 问题。

socket() creates an endpoint for communication and returns a descriptor.

The domain parameter specifies a communication domain; this selects the protocol family which will be used for communication. These families are

defined in <sys/socket.h>. The currently understood formats include:

Name Purpose Man page

PF_UNIX, PF_LOCAL Local communication unix(7)

PF_INET IPv4 Internet protocols ip(7)

PF_INET6 IPv6 Internet protocols

PF_IPX IPX - Novell protocols

PF_NETLINK Kernel user interface device netlink(7)

PF_X25 ITU-T X.25 / ISO-8208 protocol x25(7)

PF_AX25 Amateur radio AX.25 protocol

PF_ATMPVC Access to raw ATM PVCs

PF_APPLETALK Appletalk ddp(7)

PF_PACKET Low level packet interface packet(7)

The socket has the indicated type, which specifies the communication semantics. Currently defined types are:

SOCK_STREAM

Provides sequenced, reliable, two-way, connection-based byte streams. An out-of-band data transmission mechanism may be supported.

SOCK_DGRAM

Supports datagrams (connectionless, unreliable messages of a fixed maximum length).

SOCK_SEQPACKET

Provides a sequenced, reliable, two-way connection-based data transmission path for datagrams of fixed maximum length; a consumer is required to

read an entire packet with each read system call.

SOCK_RAW

Provides raw network protocol access.

SOCK_RDM

Provides a reliable datagram layer that does not guarantee ordering.

SOCK_PACKET

Obsolete and should not be used in new programs; see packet(7).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: