Search code examples
cwirelesspcaplibpcappacket-capture

C: libpcap doesn't capture wlan0 packets


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.


Solution

  • pcap_next() returns a pointer to the packet data on success, and returns NULL if an error occured, or if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a read timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read), or if no more packets are available in a ''savefile.'' Unfortunately, there is no way to determine whether an error occured or not.

    http://linux.die.net/man/3/pcap_next

    So it could be allright. My suggestion is to check for NULL, do nothing (or i--;) and go on with the next packet. OR use pcap_next_ex() and check for an error.
    And does the pcap_open_live() even return a valid handle? Please check the return value.