首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

icmp协议 ping编程实现

icmp协议 ping编程实现

ICMP(Internet ControlMessage,网际控制报文协议)是为网关和目标主机而提供的一种差错控制机制,使它们在遇到差错时能把错误报告给报文源发方。ICMP协议是IP层的一个协议,但是由于差错报告在发送给报文源发方时可能也要经过若干子网,因此牵涉到路由选择等问题,所以ICMP报文需通过IP协议来发送。ICMP数据报的数据发送前需要两级封装:首先添加ICMP报头形成ICMP报文,再添加IP报头形成IP数据报。如下所示

IP报头 ICMP报头  ICMP数据报

IP报头格式:
由于IP层协议是一种点对点的协议,而非端对端的协议,它提供无连接的数据报服务,没有端口的概念,因此很少使用bind()和connect()函数,若有使用也只是用于设置IP地址。发送数据使用sendto()函数,接收数据使用recvfrom()函数。

在Linux中,IP报头格式数据结构()定义如下:
struct ip
{
    #if __BYTE_ORDER == __LITTLE_ENDIAN
    unsigned int ip_hl:4;  
    unsigned int ip_v:4;   
    #endif
    #if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int ip_v:4;   
    unsigned int ip_hl:4;  
    #endif
    u_int8_tip_tos;   
    u_shortip_len;     
    u_shortip_id;      
    u_shortip_off;     
    #define IP_RF 0x8000  
    #define IP_DF 0x4000  
    #define IP_MF 0x2000  
    #define IP_OFFMASK 0x1fff  
    u_int8_t ip_ttl;   
    u_int8_tip_p;     
    u_shortip_sum;   
    struct in_addr ip_src,ip_dst;  
};

其中ping程序只使用以下数据:
IP报头长度IHL(Internet HeaderLength)――以4字节为一个单位来记录IP报头的长度,是上述IP数据结构的ip_hl变量。
生存时间TTL(Time ToLive)――以秒为单位,指出IP数据报能在网络上停留的最长时间,其值由发送方设定,并在经过路由的每一个节点时减一,当该值为0时,数据报将被丢弃,是上述IP数据结构的ip_ttl变量。

ICMP报头格式 :
ICMP报文分为两种,一是错误报告报文,二是查询报文。每个ICMP报头均包含类型、编码和校验和这三项内容,长度为8位,8位和16位,其余选项则随ICMP的功能不同而不同。
Ping命令只使用众多ICMP报文中的两种:"请求回送"(ICMP_ECHO)和"请求回应"(ICMP_ECHOREPLY)。在Linux中定义如下:(见ICMP TYPE CODE 对应关系一节)
#define ICMP_ECHO 0
#define ICMP_ECHOREPLY8   

在Linux中ICMP数据结构()定义如下:
struct icmp
{
u_int8_t icmp_type;
u_int8_t icmp_code;
u_int16_t icmp_cksum;
union
{
u_char ih_pptr;
struct in_addr ih_gwaddr;
struct ih_idseq
{
u_int16_t icd_id;
u_int16_t icd_seq;
} ih_idseq;
u_int32_t ih_void;


struct ih_pmtu
{
u_int16_t ipm_void;
u_int16_t ipm_nextmtu;
} ih_pmtu;

struct ih_rtradv
{
u_int8_t irt_num_addrs;
u_int8_t irt_wpa;
u_int16_t irt_lifetime;
} ih_rtradv;
} icmp_hun;
#define icmp_pptr icmp_hun.ih_pptr
#define icmp_gwaddr icmp_hun.ih_gwaddr
#define icmp_id icmp_hun.ih_idseq.icd_id
#define icmp_seq icmp_hun.ih_idseq.icd_seq
#define icmp_void icmp_hun.ih_void
#define icmp_pmvoid icmp_hun.ih_pmtu.ipm_void
#define icmp_nextmtu icmp_hun.ih_pmtu.ipm_nextmtu
#define icmp_num_addrs icmp_hun.ih_rtradv.irt_num_addrs
#define icmp_wpa icmp_hun.ih_rtradv.irt_wpa
#define icmp_lifetime icmp_hun.ih_rtradv.irt_lifetime
union
{
struct
{
u_int32_t its_otime;
u_int32_t its_rtime;
u_int32_t its_ttime;
} id_ts;
struct
{
struct ip idi_ip;

} id_ip;
struct icmp_ra_addr id_radv;
u_int32_t id_mask;
u_int8_t id_data[1];
} icmp_dun;
#define icmp_otime icmp_dun.id_ts.its_otime
#define icmp_rtime icmp_dun.id_ts.its_rtime
#define icmp_ttime icmp_dun.id_ts.its_ttime
#define icmp_ip icmp_dun.id_ip.idi_ip
#define icmp_radv icmp_dun.id_radv
#define icmp_mask icmp_dun.id_mask
#define icmp_data icmp_dun.id_data
};
继承事业,薪火相传
返回列表