请输入您要查询的百科知识:

 

词条 pcap
释义

packet capture library抓包库

这个抓包库给抓包系统提供了一个高层次的接口。所有网络上的数据包,甚至是那些发送给其他主机的,通过这种机制,都是可以捕获的。它也支持把捕获的数据包保存为本地文件和从本地文件读取信息。

工作流程

1.打开网络接口

这一步需要告诉程序我们的网卡接口,或者让程序自己检测。

下面这段程序检测系统中所有可用的网卡接口并且逐一打印名称和描述信息。

注意:由于是底层的系统调用,所以需要root权限。否则系统会检测不到网卡。

pcap_findalldevs();

代码:

#include <pcap.h>

#include <stdlib.h>

#include <stdio.h>

int main(int argc, char *argv[])

{

pcap_if_t *alldevs;

pcap_if_t *device;

char errbuf[PCAP_ERRBUF_SIZE];

if(pcap_findalldevs(&alldevs, errbuf) == -1)

{

fprintf(stderr, "Error in pcap_findalldevs: %s\", errbuf);

exit(EXIT_FAILURE);

}

device = alldevs;

for(; device != NULL; device = device->next)

{

printf("Device name: %s\", device->name);

printf("Description: %s\", device->description);

}

/* 不再需要设备列表了,释放它 */

pcap_freealldevs(alldevs);

return 0;

}

个人不推荐用,官方也不推荐用pcap_lookupdev()来找网卡,windows 环境推荐 pcap_findalldevs_ex() 。

2.初始化

3.设置捕获规则

打开文件句柄使用

pcap_t *handle;

handle = pcap_open_live(device, 1000, 1, 1000, errbuf);

if(handle == NULL)

{

fprintf(stderr, "Open device : %s failed: %s\", device, errbuf);

exit(EXIT_FAILURE);

}

sprintf(filter_exp, "ether dst//这里是mac地址: %02x:%02x:%02x:%02x:%02x:%02x"

" and ether proto 0x8812//这里是protocol协议",

mac[0],mac[1],

mac[2], mac[3],

mac[4], mac[5]);

//编译规则

if (pcap_compile(handle, &fp, filter_exp, 0, 0) == -1) {

fprintf(stderr, "Couldn't parse filter %s: %s\",

filter_exp, pcap_geterr(handle));

exit(EXIT_FAILURE);

}

//应用规则

if (pcap_setfilter(handle, &fp) == -1) {

fprintf(stderr, "Couldn't install filter %s: %s\",

filter_exp, pcap_geterr(handle));

exit(EXIT_FAILURE);

}

pcap_freecode(&fp);

pcap_freealldevs(alldevs);

pcap_setfilter();

4.开始进入抓包循环

pcap_loop();

5.关闭会话

pcap_close();

随便看

 

百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。

 

Copyright © 2004-2023 Cnenc.net All Rights Reserved
更新时间:2025/2/27 12:06:13