linux c抓包,基于Linux C的socket抓包程序和Package分析

测试运行平台:CentOS 6.5发行版,内核版本3.11

3. 利用wireshark分析数据包

如果要使用wireshark分析数据包,则应将抓取到的数据按照pcap文件指定格式存储到文件中。

附:安装wireshark

sudo yum install wireshark

sudo yum install wireshak-gnome

(1)pcap文件头格式的结构体定义如下。

typedef struct pcap_file_hdr {

u_int32 magic;

u_short ver_major;

u_short ver_minor;

int32 timezone;

u_int32 sigfigs;

u_int32 snaplen;

u_int32 linktype;

}__attribute__((packed))PCAP_FILE_HDR;

(2)pcap每一条数据记录都应有数据包头,其定义如下。

typedef struct pcap_pkg_hdr {

u_int32 time_sec;  //this represents the number of whole seconds of elapsed time.

u_int32 time_usec;  //this is the rest of the elapsed time, represent it as a number of microseconds.

u_int32 caplen;

u_int32 len;

}__attribute__((packed)) PCAP_PKG_HDR;

在文件中写入数据包头后,即可将数据(buf)直接写入到文件中了。下面是一段生成cap文件的代码。

PCAP_FILE_HDR pcap_file_hdr = {0};

PCAP_PKG_HDR pcap_pkg_hdr = {0};

struct timeval ts;

File *pfile = NULL;

pfile = fopen(fname.pcap, "wb");

if(pfile == NULL){

fprintf(stdout, "no file will be saved.\n");

}else{

pcap_file_hdr->magic = 0xa1b2c3d4;  //0xA1B2C3D4是pcap文件的固定文件识别头

pcap_file_hdr->ver_major = 0x02;

pcap_file_hdr->ver_minor = 0x04;

pcap_file_hdr->timezone = 0x00;

pcap_file_hdr->sigfigs = 0x00;

pcap_file_hdr->snaplen = 0xff;

pcap_file_hdr->linktype = 0x01;

fwrite(&pcap_file_hdr, sizeof(pcap_file_hdr), 1, pfile);

}

while(1){

n_rd = recvfrom(SOCKET_SRC, buf, BUFFER_MAX, 0, NULL, NULL); //returns the number of bytes received

if(n_rd < 46){

fprintf(stdout, "Incomplete header, packet corrupt\n");

continue;

}

printf("pkg size[%d] \n", n_rd);

if(pfile != NULL) {

gettimeofday(&ts, NULL);

pcap_pkg_hdr->time_usec = ts.tv_usec;

pcap_pkg_hdr->time_sec = ts.tv_sec;

pcap_pkg_hdr->caplen = sz;

pcap_pkg_hdr->len =sz;

fwrite(&pcap_pkg_hdr, sizeof(pcap_pkg_hdr), 1, pfile);

fwrite(buf, n_rd, 1, pfile);

}

/* termination control */

}

程序执行完成后,会发现在当前目录下生成了 fname.pcap文件,在shell中输入命令

wireshark fname.pcap

即可使用wireshark打开并观察数据包了。

0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值