PCAP -- The Portable Packet Cature Library


Pcap is a portable interface to raw socket interface. 

Resources:

The basics of pcap is the idea of a packet stream.  You open the packet stream, read from the stream, and then close the stream.  There are two ways to open a packet stream.

Once you have the stream open you can read packets.  There are several methods to do this.  The easiest and most powerful and best is

Here are some notes ...


Below is a sample working pcap program.  IT MUST BE RUN AS ROOT.
#include <pcap.h>
#include <stdio.h>
#include <iostream>
using namespace std;

int main()
{
        pcap_t *handle;                                  /* Session handle */
        char errbuf[PCAP_ERRBUF_SIZE];    /* Error string */
        struct pcap_pkthdr *header;               /* The header that pcap gives us */
        const u_char *packet;                        /* The actual packet */

        /* Open the session in promiscuous mode */
        handle = pcap_open_live("eth0", 65000, 0, 0, errbuf);
        if (handle == 0)  {
                cout << "Error in pcap_open_live: " << errbuf << endl;
                exit(1);
        }

        /* Grab a packet */
        int code  = pcap_next_ex(handle, &header, &packet);
        if (code < 0)
                cout << "Error in pcap_next_ex\n";

        /* Print its length */
        cout << "Jacked a packet with length of " << header->len << " bytes\n";

        /* And close the session */
        pcap_close(handle);
        return(0);
}