Graphics Programs Reference
In-Depth Information
Now that the headers are defined as structures, we can write a program
to decode the layered headers of each packet. But before we do, let's talk
about libpcap for a moment. This library has a function called pcap_loop() ,
which is a better way to capture packets than just looping on a pcap_next()
call. Very few programs actually use pcap_next() , because it's clumsy and
inefficient. The pcap_loop() function uses a callback function. This means
the pcap_loop() function is passed a function pointer, which is called every
time a packet is captured. The prototype for pcap_loop() is as follows:
i nt pcap_loop(pcap_t *handle, int count, pcap_handler callback, u_char *args);
The first argument is the pcap's handle, the next one is a count of how
many packets to capture, and the third is a function pointer to the callback
function. If the count argument is set to -1 , it will loop until the program
breaks out of it. The final argument is an optional pointer that will get
passed to the callback function. Naturally, the callback function needs to
follow a certain prototype, since pcap_loop() must call this function. The
callback function can be named whatever you like, but the arguments must
be as follows:
void callback(u_char *args, const struct pcap_pkthdr *cap_header, const u_char *packet);
The first argument is just the optional argument pointer from the last
argument to pcap_loop() . It can be used to pass additional information to the
callback function, but we aren't going to be using this. The next two arguments
should be familiar from pcap_next() : a pointer to the capture header and a
pointer to the packet itself.
The following example code uses pcap_loop() with a callback function to
capture packets and our header structures to decode them. This program will
be explained as the code is listed.
decode_sniff.c
#include <pcap.h>
#include "hacking.h"
#include "hacking-network.h"
void pcap_fatal(const char *, const char *);
void decode_ethernet(const u_char *);
void decode_ip(const u_char *);
u_int decode_tcp(const u_char *);
void caught_packet(u_char *, const struct pcap_pkthdr *, const u_char *);
int main() {
struct pcap_pkthdr cap_header;
const u_char *packet, *pkt_data;
char errbuf[PCAP_ERRBUF_SIZE];
char *device;
Search WWH ::




Custom Search