ICMP(Internet Control Message,網際控制報文協議)是為網關和目標主機而提供的一種差錯控制機制,使它們在碰到差錯時能把錯誤報告給報文源發方。ICMP協議是IP層的一個協議,但是由于差錯報告在發送給報文源發方時可能也要經過若干子網,因此牽涉到路由選擇等問題,所以ICMP報文需通過IP協議來發送。ICMP數據報的數據發送前需要兩級封裝:首先添加ICMP報頭形成ICMP報文,再添加IP報頭形成IP數據報。如下圖所示
在Linux中,IP報頭格式數據結構()定義如下: strUCt ip { #if __BYTE_ORDER == __LITTLE_ENDIAN unsigned int ip_hl:4; /* header length */ unsigned int ip_v:4; /* version */ #endif #if __BYTE_ORDER == __BIG_ENDIAN unsigned int ip_v:4; /* version */ unsigned int ip_hl:4; /* header length */ #endif u_int8_t ip_tos; /* type of service */ u_short ip_len; /* total length */ u_short ip_id; /* identification */ u_short ip_off; /* fragment offset field */ #define IP_RF 0x8000 /* reserved fragment flag */ #define IP_DF 0x4000 /* dont fragment flag */ #define IP_MF 0x2000 /* more fragments flag */ #define IP_OFFMASK 0x1fff /* mask for fragmenting bits */ u_int8_t ip_ttl; /* time to live */ u_int8_t ip_p; /* PRotocol */ u_short ip_sum; /* checksum */ struct in_addr ip_src, ip_dst; /* source and dest address */ };
其中ping程序只使用以下數據:
IP報頭長度IHL(Internet Header Length)――以4字節為一個單位來記錄IP報頭的長度,是上述IP數據結構的ip_hl變量。 生存時間TTL(Time To Live)――以秒為單位,指出IP數據報能在網絡上停留的最長時間,其值由發送方設定,并在經過路由的每一個節點時減一,當該值為0時,數據報將被丟棄,是上述IP數據結構的ip_ttl變量
退出root,用一般用戶登陸,執行./myping www.cn.ibm.com,有以下執行結果: PING www.cn.ibm.com(202.95.2.148): 56 bytes data in ICMP packets. 64 byte from 202.95.2.148: icmp_seq=1 ttl=242 rtt=3029.000 ms 64 byte from 202.95.2.148: icmp_seq=2 ttl=242 rtt=2020.000 ms 64 byte from 202.95.2.148: icmp_seq=3 ttl=242 rtt=1010.000 ms
--------------------PING statistics------------------- 3 packets transmitted, 3 received , %0 lost