I'm new in C and got little confused. I've read some topics about this problem but none of them worked for me. I'm trying to capture wlan0 packets with libpcap but something goes wrong. pcap_next() function returns null but i can't figure out why. Here is my code:
#include <pcap.h>
#include <stdio.h>
#include <string.h>
void dump(const unsigned char *data_buffer, const unsigned int length) {
unsigned char byte;
unsigned int i, j;
for(i=0; i < length; i++) {
byte = data_buffer[i];
printf("%02x ", data_buffer[i]); // Display byte in hex.
if(((i%16)==15) || (i==length-1)) {
for(j=0; j < 15-(i%16); j++)
printf(" ");
printf("| ");
for(j=(i-(i%16)); j <= i; j++) { // Display printable bytes from line.
byte = data_buffer[j];
if((byte > 31) && (byte < 127)) // Outside printable char range
printf("%c", byte);
else
printf(".");
}
printf("\n"); // End of the dump line (each line is 16 bytes)
} // End if
} // End for
}
int main() {
struct pcap_pkthdr header;
const u_char *packet;
char errbuf[PCAP_ERRBUF_SIZE];
char *device;
pcap_t *pcap_handle;
int i;
device = "wlan0";
printf("Sniffing on device %s\n", device);
pcap_handle = pcap_open_live(device, 4096, 1, 0, errbuf);
for(i=0; i < 3; i++) {
packet = pcap_next(pcap_handle, &header);
printf("Got a %d byte packet\n", header.len);
dump(packet, header.len);
}
pcap_close(pcap_handle);
}
what i get as output is
Sniffing on device wlan0
Got a 0 byte packet
Got a 0 byte packet
Got a 0 byte packet
This is how i compile gcc -o test test.c -l pcap and run the program as root. Thanks.
errbuf
is filled in with an appropriate error message. – bishop