请用C语言实现指定网卡向外发出指定端口指定抓包数量并存到pcap文件的程序
时间: 2024-03-14 20:49:47 浏览: 174
网络抓包winpcap版本C语言实现
4星 · 用户满意度95%
以下是一个基于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;
int count, port;
struct bpf_program fp;
bpf_u_int32 net, mask;
struct pcap_pkthdr header;
const u_char *packet;
char filename[100];
if (argc != 4) {
printf("Usage: %s <devname> <port> <count>\n", argv[0]);
exit(1);
}
devname = argv[1];
port = atoi(argv[2]);
count = atoi(argv[3]);
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_%d.pcap", devname, port);
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, "tcp port %d", port);
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 (i < count) {
packet = pcap_next(handle, &header);
if (packet == NULL) {
continue;
}
char *data = (char *)(packet + sizeof(struct ether_header) + sizeof(struct iphdr) + sizeof(struct tcphdr));
int data_len = header.len - sizeof(struct ether_header) - sizeof(struct iphdr) - sizeof(struct tcphdr);
// write packet to file
fwrite(packet, 1, header.len, fp_out);
fflush(fp_out);
printf("Captured packet %d, length %d: %s\n", i + 1, header.len, data);
i++;
}
fclose(fp_out);
pcap_close(handle);
return 0;
}
```
程序的运行参数为指定的网卡名称、指定的端口号和所需捕获的数据包数量。程序会打开指定的网卡设备,并使用libpcap编译和设置一个BPF过滤器,以仅捕获目标端口的TCP数据包。程序会捕获指定数量的数据包,并将它们写入一个pcap文件中。
阅读全文