#include #include #include #include #include #include #include void * messageArrival(u_char *args, const struct pcap_pkthdr *header, const u_char *packet); int main(int argc, char **argv) { pcap_t *handle; /* Session handle */ char *dev; /* The device to sniff on */ char errbuf[PCAP_ERRBUF_SIZE]; /* Error string */ bpf_u_int32 net; /* Our IP */ bpf_u_int32 mask; /* Our netmask */ struct bpf_program filter; /* The compiled filter */ char filter_app[64]; /* The filter expression */ /* clear error buffer */ memset(errbuf, 0, PCAP_ERRBUF_SIZE); /* find valid device on machine */ if ((dev = pcap_lookupdev(errbuf)) == NULL) { fprintf(stderr, "pcap_lookupdev failed: %s\n", errbuf); return -1; } /* Find the properties for the device */ if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) { fprintf(stderr, "pcap_lookupnet failed: %s\n", errbuf); return -2; } /* Open the session in promiscuous mode */ if ((handle = pcap_open_live(dev, BUFSIZ, 1, 0, errbuf)) == NULL) { fprintf(stderr, "pcap_open_live failed: %s\n", errbuf); return -3; } /* Construct the filter */ sprintf(filter_app, "%s", "tcp or udp"); /* Compile the filter into pcap form */ if (pcap_compile(handle, &filter, filter_app, 0, net) == -1) { fprintf(stderr, "pcap_compile failed: %s\n", pcap_geterr(handle)); return -4; } /* Apply the filter */ if (pcap_setfilter(handle, &filter) == -1) { fprintf(stderr, "pcap_setfilter failed: %s\n", pcap_geterr(handle)); return -5; } /* Grab packets until the cows come home */ pcap_loop(handle, -1, (pcap_handler)messageArrival, ""); /* pcap_loop returns only on error */ pcap_close(handle); /* if pcap returned, we failed somewhere */ return -1; } void * messageArrival(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) { printf("messaage received: %d\n", header->len); return (void *)NULL; }