Created
April 9, 2013 08:49
-
-
Save physacco/5344127 to your computer and use it in GitHub Desktop.
A "hello world" example for libpcap.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pcap/pcap.h> | |
/* callback function when packet have captured */ | |
static void mycb(u_char *user, | |
const struct pcap_pkthdr *h, const u_char *packet) | |
{ | |
static int count = 1; | |
printf("Packet %d:\n", count); | |
printf(" user: %x\n", user); | |
printf(" h: %x\n", h); | |
printf(" h->ts: %d.%d\n", h->ts.tv_sec, h->ts.tv_usec); | |
printf(" h->caplen: %d\n", h->caplen); | |
printf(" h->len: %d\n", h->len); | |
printf(" packet: %x\n", packet); | |
if(count >= 3) { | |
pcap_breakloop((pcap_t*)user); | |
} else { | |
count += 1; | |
} | |
} | |
int main (int argc, char* argv[]) | |
{ | |
/* the error code buf of libpcap, PCAP_ERRBUF_SIZE = 256 */ | |
char ebuf[PCAP_ERRBUF_SIZE]; | |
char *dev; | |
pcap_t *pd; | |
int pcap_loop_ret; | |
/* grab a device to peak into */ | |
dev = pcap_lookupdev(ebuf); | |
if(dev == NULL) { | |
/* e.g. "no suitable device found" */ | |
printf("pcap_lookupdev error: %s\n", ebuf); | |
abort(); | |
} else { | |
printf("pcap_lookupdev returned: %s\n", dev); | |
} | |
/* create capture handler of libpcap */ | |
pd = pcap_open_live(dev, 1024, 0, 1000, ebuf); | |
if(pd == NULL) { | |
/* e.g. "Operation not permitted" */ | |
printf("pcap_open_live error: %s\n", ebuf); | |
abort(); | |
} | |
/* start the loop of capture, loop 5 times */ | |
pcap_loop_ret = pcap_loop(pd, 5, mycb, (u_char*)pd); | |
printf("pcap_loop returned: %d\n", pcap_loop_ret); | |
pcap_close(pd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
compile: gcc -o test_pcap test_pcap.c -lpcap