能否用C++捕获ICMP数据包

   2024-09-30 7640
核心提示:是的,你可以使用C++来捕获ICMP数据包#includeiostream#include pcap.h#include netinet/ip.h#include netinet/ip_icmp.hvoid pr

是的,你可以使用C++来捕获ICMP数据包

#include<iostream>#include <pcap.h>#include <netinet/ip.h>#include <netinet/ip_icmp.h>void processPacket(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {    struct ip *ipHeader = (struct ip *)(packet + sizeof(struct ether_header));    struct icmp *icmpHeader = (struct icmp *)(packet + sizeof(struct ether_header) + (ipHeader->ip_hl << 2));    std::cout << "ICMP packet received: type=" << (int)icmpHeader->icmp_type << ", code=" << (int)icmpHeader->icmp_code<< std::endl;}int main() {    char *device = pcap_lookupdev(nullptr);    if (device == nullptr) {        std::cerr << "Error finding device"<< std::endl;        return 1;    }    char errorBuffer[PCAP_ERRBUF_SIZE];    pcap_t *handle = pcap_open_live(device, BUFSIZ, 1, 1000, errorBuffer);    if (handle == nullptr) {        std::cerr << "Error opening device: "<< errorBuffer<< std::endl;        return 1;    }    struct bpf_program filter;    if (pcap_compile(handle, &filter, "icmp", 0, PCAP_NETMASK_UNKNOWN) == -1) {        std::cerr << "Error compiling filter: " << pcap_geterr(handle)<< std::endl;        return 1;    }    if (pcap_setfilter(handle, &filter) == -1) {        std::cerr << "Error setting filter: " << pcap_geterr(handle)<< std::endl;        return 1;    }    pcap_loop(handle, -1, processPacket, nullptr);    pcap_freecode(&filter);    pcap_close(handle);    return 0;}

这个示例程序首先查找一个网络设备(如eth0),然后使用pcap_open_live函数打开该设备。接下来,它编译并设置一个过滤器,以便只捕获ICMP数据包。最后,它使用pcap_loop函数循环捕获数据包,并在每次捕获到ICMP数据包时调用processPacket回调函数。

请注意,这个示例程序需要root权限才能运行,因为捕获数据包通常需要访问受保护的系统资源。

要编译此程序,你需要安装libpcap库,并在编译命令中链接它。例如,在Linux上,你可以使用以下命令编译程序:

g++ -o capture_icmp capture_icmp.cpp -lpcap

然后,你可以使用以下命令运行程序:

sudo ./capture_icmp

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号