Capturing packets
In this recipe, we will show you how to use the libpcap library to capture packets. We will also introduce some basic libpcap concepts, such as the pcap
handler and filters.
Getting ready
Prior to running this recipe, we need to follow the Adding libpcap to your project recipe presented earlier in this chapter.
How to do it…
Let's capture some packets by following the ensuing steps:
We start off by defining the following three symbols for use in our code:
#define SNAPLEN 65535 #define PROMISC 1 #define TIMEOUT 500
The
SNAPLEN
constant defines the maximum size of the packet to be captured. ThePROMISC
constant specifies whether we want to set the interface to the promiscuous mode or not;1
is true and0
is false. TheTIMEOUT
constant is the read timeout in milliseconds.We need to define the following variables:
pcap_t *handle; char errbuf[PCAP_ERRBUF_SIZE]; bpf_u_int32 localNet, netMask; struct bpf_program filterCode; char filter[] = "arp or tcp or udp or icmp";
The three variables...