写一个pcap包提取五元组的c++
时间: 2023-05-20 14:00:48 浏览: 297
非常感谢您的提问!以下是一个简单的C代码,可以提取pcap包中的五元组:
#include <stdio.h> #include <pcap.h> #include <netinet/in.h>
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data);
int main(int argc, char **argv) { char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *handle; struct bpf_program fp; char filter_exp[] = "ip"; bpf_u_int32 net, mask;
if (argc != 2) {
printf("Usage: %s <pcap_file>\n", argv[0]);
return 1;
}
handle = pcap_open_offline(argv[1], errbuf);
if (handle == NULL) {
printf("Error opening pcap file: %s\n", errbuf);
return 1;
}
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
printf("Error compiling filter: %s\n", pcap_geterr(handle));
return 1;
}
if (pcap_setfilter(handle, &fp) == -1) {
printf("Error setting filter: %s\n", pcap_geterr(handle));
return 1;
}
pcap_loop(handle, 0, packet_handler, NULL);
pcap_close(handle);
return 0;
}
void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data) { struct iphdr *ip_hdr; struct tcphdr *tcp_hdr; struct udphdr *udp_hdr; struct in_addr src_addr, dst_addr; u_short src_port, dst_port;
ip_hdr = (struct iphdr *)(pkt_data + sizeof(struct ether_header));
src_addr.s_addr = ip_hdr->saddr;
dst_addr.s_addr = ip_hdr->daddr;
if (ip_hdr->protocol == IPPROTO_TCP) {
tcp_hdr = (struct tcphdr *)(pkt_data + sizeof(struct ether_header) + sizeof(struct iphdr));
src_port = ntohs(tcp_hdr->source);
dst_port = ntohs(tcp_hdr->dest);
printf("TCP %s:%d -> %s:%d\n", inet_ntoa(src_addr), src_port, inet_ntoa(dst_addr), dst_port);
} else if (ip_hdr->protocol == IPPROTO_UDP) {
udp_hdr = (struct udphdr *)(pkt_data + sizeof(struct ether_header) + sizeof(struct iphdr));
src_port = ntohs(udp_hdr->source);
dst_port = ntohs(udp_hdr->dest);
printf("UDP %s:%d -> %s:%d\n", inet_ntoa(src_addr), src_port, inet_ntoa(dst_addr), dst_port);
}
}
希望这个代码能够帮助您提取pcap包中的五元组!
相关推荐

















