Cyrine Nasri
Cyrine Nasri

Reputation: 23

reading a tcpdump file with C++

Actually I'm trying to capture trafic with TCPdumpand redirect result in a file (.pcap) my first problem is how to read MAC address IP address and Signal strenghfrom the .pcap using C++.

Second problem is that I want to scan trafic from a specefic MAC address, then be able to change it with another MAC address here is what my tcpdump:

sudo tcpdump -i wlan0 -e ether host 90:B6:86:15:A9:DB -vvv -w capture.pcap

Upvotes: 1

Views: 1206

Answers (2)

Mikolasan
Mikolasan

Reputation: 785

I will answer how to read MAC address and IP address from the .pcap using C++. This is a minimal working example, I specifically stripped all error handling and such.

#include <iomanip>
#include <iostream>
#include <pcap/pcap.h>

#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/udp.h>

int main(int argc, char const *argv[])
{
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* handle = pcap_open_offline("dump.pcap", errbuf);
    struct pcap_pkthdr* header;
    const u_char* packet;
    int result = 0;
    do {
        result = pcap_next_ex(handle, &header, &packet);
        if (result == PCAP_ERROR_BREAK) break;

        // Ethernet layer
        const struct ether_header* ethernet_header = reinterpret_cast<const struct ether_header*>(packet);
        std::cout << "Source MAC: ";
        for (int i = 0; i < ETH_ALEN; ++i) {
            std::cout << std::setfill('0') << std::setw(2) << std::hex << std::uppercase 
                << static_cast<int>(ethernet_header->ether_shost[i]);
            if (i < ETH_ALEN - 1) std::cout << ":";
        }
        std::cout << std::endl;

        std::cout << "Destination MAC: ";
        for (int i = 0; i < ETH_ALEN; ++i) {
            std::cout << std::setfill('0') << std::setw(2) << std::hex << std::uppercase 
                << static_cast<int>(ethernet_header->ether_dhost[i]);
            if (i < ETH_ALEN - 1) std::cout << ":";
        }
        std::cout << std::endl;
        
        if (ntohs(ethernet_header->ether_type) == ETHERTYPE_IP) {
            // IP level
            const struct ip* ip_header = (struct ip*)(packet + sizeof(struct ether_header));
            char source_ip[INET_ADDRSTRLEN];
            char dest_ip[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, &(ip_header->ip_src), source_ip, INET_ADDRSTRLEN);
            inet_ntop(AF_INET, &(ip_header->ip_dst), dest_ip, INET_ADDRSTRLEN);
            std::cout << "Source IP: " << source_ip << std::endl;
            std::cout << "Destination IP: " << dest_ip << std::endl;
        }

    } while (result == 1);

    pcap_close(handle);
    return 0;
}

Reference

Upvotes: 0

arved
arved

Reputation: 4576

The library for dealing with pcap files is called libpcap.

For starters a tutorial can be found here: http://www.tcpdump.org/pcap.html

Upvotes: 2

Related Questions