Graphics Programs Reference
In-Depth Information
0x442
libpcap Sniffer
A standardized programming library called libpcap can be used to smooth
out the inconsistencies of raw sockets. The functions in this library still use
raw sockets to do their magic, but the library knows how to correctly work
with raw sockets on multiple architectures. Both tcpdump and dsniff use
libpcap, which allows them to compile with relative ease on any platform.
Let's rewrite the raw packet sniffer program using the libpcap's functions
instead of our own. These functions are quite intuitive, so we will discuss
them using the following code listing.
pcap_sniff.c
#include <pcap.h>
#include "hacking.h"
void pcap_fatal(const char *failed_in, const char *errbuf) {
printf("Fatal Error in %s: %s\n", failed_in, errbuf);
exit(1);
}
First, pcap.h is included providing various structures and defines used by
the pcap functions. Also, I've written a pcap_fatal() function for displaying
fatal errors. The pcap functions use a error buffer to return error and status
messages, so this function is designed to display this buffer to the user.
int main() {
struct pcap_pkthdr header;
const u_char *packet;
char errbuf[PCAP_ERRBUF_SIZE];
char *device;
pcap_t *pcap_handle;
int i;
The errbuf variable is the aforementioned error buffer, its size coming
from a define in pcap.h set to 256 . The header variable is a pcap_pkthdr structure
containing extra capture information about the packet, such as when it was
captured and its length. The pcap_handle pointer works similarly to a file
descriptor, but is used to reference a packet-capturing object.
device = pcap_lookupdev(errbuf);
if(device == NULL)
pcap_fatal("pcap_lookupdev", errbuf);
printf("Sniffing on device %s\n", device);
The pcap_lookupdev() function looks for a suitable device to sniff on. This
device is returned as a string pointer referencing static function memory. For
our system this will always be /dev/eth0 , although it will be different on a BSD
system. If the function can't find a suitable interface, it will return NULL .
Search WWH ::




Custom Search