Ping code 实现分享

   很久之前参阅文档写了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
{ <
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值