溫馨提示×

能否用C++捕獲ICMP數(shù)據(jù)包

c++
小樊
82
2024-09-10 17:39:55
欄目: 編程語言

是的,你可以使用C++來捕獲ICMP數(shù)據(jù)包

#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;
}

這個(gè)示例程序首先查找一個(gè)網(wǎng)絡(luò)設(shè)備(如eth0),然后使用pcap_open_live函數(shù)打開該設(shè)備。接下來,它編譯并設(shè)置一個(gè)過濾器,以便只捕獲ICMP數(shù)據(jù)包。最后,它使用pcap_loop函數(shù)循環(huán)捕獲數(shù)據(jù)包,并在每次捕獲到ICMP數(shù)據(jù)包時(shí)調(diào)用processPacket回調(diào)函數(shù)。

請注意,這個(gè)示例程序需要root權(quán)限才能運(yùn)行,因?yàn)椴东@數(shù)據(jù)包通常需要訪問受保護(hù)的系統(tǒng)資源。

要編譯此程序,你需要安裝libpcap庫,并在編譯命令中鏈接它。例如,在Linux上,你可以使用以下命令編譯程序:

g++ -o capture_icmp capture_icmp.cpp -lpcap

然后,你可以使用以下命令運(yùn)行程序:

sudo ./capture_icmp

0