C语言实现抓指定网卡向外发出的pcap包
时间: 2024-03-14 07:47:32 浏览: 63
以下是一个基于libpcap库的C语言程序,可以实现指定网卡向外发出的数据包捕获,并将捕获的数据包存储到pcap文件中。
```c
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <string.h>
#define BUFSIZE 65536
int main(int argc, char *argv[])
{
char *devname, errbuf[PCAP_ERRBUF_SIZE];
pcap_t *handle;
struct bpf_program fp;
bpf_u_int32 net, mask;
struct pcap_pkthdr header;
const u_char *packet;
char filename[100];
if (argc != 2) {
printf("Usage: %s <devname>\n", argv[0]);
exit(1);
}
devname = argv[1];
if (pcap_lookupnet(devname, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Can't get netmask for device %s\n", devname);
net = 0;
mask = 0;
}
handle = pcap_open_live(devname, BUFSIZE, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", devname, errbuf);
exit(1);
}
snprintf(filename, 100, "%s_out.pcap", devname);
FILE *fp_out = fopen(filename, "wb");
if (fp_out == NULL) {
fprintf(stderr, "Couldn't create output file %s\n", filename);
exit(1);
}
char filter_exp[100];
snprintf(filter_exp, 100, "src %s", pcap_lookupdev(errbuf));
if (pcap_compile(handle, &fp, filter_exp, 0, mask) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp, pcap_geterr(handle));
exit(1);
}
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n", filter_exp, pcap_geterr(handle));
exit(1);
}
int i = 0;
while (1) {
packet = pcap_next(handle, &header);
if (packet == NULL) {
continue;
}
// write packet to file
fwrite(packet, 1, header.len, fp_out);
fflush(fp_out);
printf("Captured packet %d, length %d\n", i + 1, header.len);
i++;
}
fclose(fp_out);
pcap_close(handle);
return 0;
}
```
程序的运行参数为指定的网卡名称。程序会打开指定的网卡设备,并使用libpcap编译和设置一个BPF过滤器,以仅捕获该网卡发出的数据包。程序会持续捕获数据包,并将它们写入一个pcap文件中。注意,如果不停止程序,它会一直运行下去,不断捕获数据包。
阅读全文