Sniffer with libpcap on Mac OS X in C

jndok picture jndok · Feb 23, 2013 · Viewed 9k times · Source

I was trying to create my own sniffer (ONLY FOR FUN), and I work on a Mac. I'm using libpcap, which is a very good library for sniffing. So, I used this simple sniffer, which sniffs 5 packets: (It is written in 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);
}

int main() {
    struct pcap_pkthdr header;
    const u_char *packet;
    char errbuf[PCAP_ERRBUF_SIZE];
    char *device;
    pcap_t *pcap_handle;
    int i;

device = pcap_lookupdev(errbuf);
if(device == NULL)
    pcap_fatal("pcap_lookupdev", errbuf);

printf("Sniffing on device %s\n", device);

pcap_handle = pcap_open_live(device, 4096, 1, 0, errbuf);
if(pcap_handle == NULL)
    pcap_fatal("pcap_open_live", errbuf);

for(i=0; i < 5; i++) {
    packet = pcap_next(pcap_handle, &header);
    printf("Got a %d byte packet\n", header.len);
    dump(packet, header.len);
}

pcap_close(pcap_handle);

}

If you're wondering, yes I took it from a book (Hacking: The Art of Exploitation) and modified a little bit. The problem is, if I run this on Linux, it works perfectly, no problems. But if I run this on a Mac, it doesn't work and it doesn't capture any packet.

Can someone of you help? Thanks in advance!

Answer

user862787 picture user862787 · Feb 24, 2013

If you're getting a "Fatal Error in pcap_lookupdev" error message, then the problem is what Sascha said it was - you don't have permission to capture packets. If you're getting that message, try running the program with sudo, or try, for example, changing the ownership of the /dev/bpf* devices to you (which you will need to do with sudo). However, you're saying that "It sniffs on 'en0'", so presumably you're saying that because it's printing "Sniffing on device en0", in which case pcap_lookupdev() isn't failing.

If you're getting a "Fatal Error in pcap_open_live", that might also be a problem with permissions, but you almost certainly wouldn't get an error due to permissions there, as pcap_lookupdev() would already have failed.

If you're not getting a "Fatal Error in" error message, the problem is probably, as Petesh noted, that you specified 0 as the timeout. If 0 is specified as the timeout, pcap_loop(), pcap_dispatch(), pcap_next(), and pcap_next_ex() can wait indefinitely before providing packets to the application; on some platforms, such as Linux and Solaris, it won't wait indefinitely, but on other platforms, such as *BSD and OS X, it could wait indefinitely. Try a timeout of 1000, which is one second; that's what tcpdump does, for example.