很久之前参阅文档写了ping实现,当时不甚在意,没有留档,导致后续需要的时候又得费力,发此code,一是留档,而是共勉,能为他人提供方便,将不甚荣幸,结构或有不够严谨,但作为ping测试却是可以了,报文结构网述颇多,这里就不再详述了
该code中icmp报文结构为自组装,适合轻量级嵌入式系统中调用
#include <stdio.h> #include <sys/time.h> #include <netdb.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/socket.h> #include <errno.h> #ifndef ICMP_ECHOREPLY #define ICMP_ECHOREPLY 0 #endif #ifndef ICMP_ECHO #define ICMP_ECHO 8 #endif #ifndef bool #define bool int #endif #ifndef true #define true 1 #endif #ifndef false #define false 0 #endif #define XM_ICMP_LEN (56 + 8) //ICMP默认数据长度 + ICMP默认头部长度 #define SEND_BUFFER_SIZE 128 //发送缓冲区大小 #define RECV_BUFFER_SIZE 128 //接收缓冲区大小 //IP报头 小端结构 第一个字节,低4位是 version 高四位是 length //IP报头 大端结构 第一个字节,低4位是 length 高四位是 version //接收报文失败,可尝试交换 ip_hl ip_v位置,或者取icmp报文时候直接跳过20个byte typedef struct xm_ip { unsigned int ip_hl:4; //header length(报头长度) unsigned int ip_v:4; //version(版本) unsigned char ip_tos; unsigned short ip_len; unsigned short ip_id; unsigned short ip_off; unsigned char ip_ttl; unsigned char ip_p; unsigned short ip_sum; struct in_addr ip_src; struct in_addr ip_dst; }IP_HEADER; struct xm_icmp { < |