要捕获流量并使用pcap格式存储,可以使用libpcap库。下面是一个使用libpcap库进行流量捕获的示例代码:
#include
#include
void packet_handler(unsigned char *user_data, const struct pcap_pkthdr *pkthdr, const unsigned char *packet) {
// 处理捕获到的每个数据包
printf("Packet captured!\n");
}
int main() {
pcap_t *handle;
char errbuf[PCAP_ERRBUF_SIZE]; // 用于存储错误消息
// 打开网络接口或pcap文件进行捕获
handle = pcap_open_live("eth0", BUFSIZ, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device: %s\n", errbuf);
return 1;
}
// 设置过滤器(可选)
struct bpf_program fp;
char filter_exp[] = "port 80"; // 只捕获目标端口为80的流量
if (pcap_compile(handle, &fp, filter_exp, 0, PCAP_NETMASK_UNKNOWN) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
return 1;
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
return 1;
}
// 开始捕获数据包
pcap_loop(handle, 0, packet_handler, NULL);
// 关闭会话
pcap_close(handle);
return 0;
}
上述代码中,pcap_open_live
函数用于打开网络接口或pcap文件进行捕获。pcap_compile
和pcap_setfilter
函数可用于设置过滤器,以便仅捕获特定的流量。pcap_loop
函数用于开始捕获数据包,并将每个捕获到的数据包传递给packet_handler
函数进行处理。最后,使用pcap_close
函数关闭会话。
请注意,上述示例代码仅提供了基本的捕获功能,你可以根据自己的需求进行修改和扩展。此外,你还需要安装libpcap库,并在编译时链接该库。