tcpdump mailing list archives

Re: Devices and adresses in libpcap


From: "David Rosal" <drosalri () gmail com>
Date: Sun, 13 Apr 2008 15:03:13 +0200

2008/4/13, Giovanni Venturi <giovanni () ksniffer org>:


You should add on the website what libpcap++ has in addition to libpcap in
details,
Giovanni


Well, libpcap++ is only a wrapper, and it does not add any new feature to
libpcap, except maybe the abbility to retrieve some attributes of pcap
descriptors that are hidden in libpcap.

In other words: all you can do with libpcap can be done with libpcap++, but
with less lines of code, and in a cleaner and safer way.

Here's a little program that captures the first 10 TCP packets seen on
interface wlan1, and writes them in a savefile called out. With error
checking, of course.

First the C version:

8<-----------------------------------------

#include <pcap.h>

static void handler(u_char *user, const struct pcap_pkthdr *header, const
u_char *datap)
{
        pcap_dump(user, header, datap);
}

int main()
{
        pcap_t* pcap;
        pcap_dumper_t* dumper;
        struct bpf_program bpf;
        char ebuf[PCAP_ERRBUF_SIZE + 1];

        if (!(pcap = pcap_open_live("wlan1", 64, 1, 0, ebuf)))
                errx("pcap_open_live(): %s", ebuf);

        if (pcap_compile(pcap, &bpf, "tcp", 0, 0) < 0)
                errx("pcap_compile(): %s", pcap_geterr(pcap));
        if (pcap_setfilter(pcap, &bpf) < 0)
                errx("pcap_setfilter(): %s", pcap_geterr(pcap));
        pcap_freecode(&bpf);

        if (!(dumper = pcap_dump_open(pcap, "out")))
                errx("pcap_dump_open(): %s", pcap_geterr(pcap));

        if (pcap_loop(pcap, 10, handler, (u_char *)dumper) < 0)
                errx("pcap_loop(): %s", pcap_geterr(pcap));

        pcap_close(pcap);
        pcap_dump_close(dumper);
}

------------------------------------------->8

Now the C++ version:

8<----------------------------------------

#include <pcap++.h>
#include <iostream>

using namespace pcappp;

void handler(Pcap& pcap, Packet const& pkt)
{
    pcap.get_dumper().dump(pkt);
}

int main()
{
    try {
        PcapLive pcap("wlan1");
        pcap.set_filter("tcp");
        pcap.get_dumper().open("out");
        pcap.loop(handler, 10);
    }
    catch (Exception& x) {
        std::cerr << x.what() << std::endl;
    }
}

-------------------------------------->8

What do you think?

I personally prefer the C++ code, since it is more brief and clear. And the
performance should be almost the same, as critical methods like
Pcap::get_dumper() have been inlined in libpcap++.

BTW: Thanks for your comment. I hace found a bug in Pcap::set_filter() while
writing the above snippets  :-P

Cheers,

    ~David
-
This is the tcpdump-workers list.
Visit https://cod.sandelman.ca/ to unsubscribe.


Current thread: