I am trying to create a sniffer that can sniff on multiple devices. In my code the program will receive a list of devices that a user wants to sniff on. I take the list of device and store it into an array that I use to loop through and pass along to a function that creates the pcap_t handle like the function below:
void *startPcapProcess(char * dev){
char errbuf[PCAP_ERRBUF_SIZE]; /* error buffer */
pcap_t *handle; /* packet capture handle */
/* filter expression [3] */
char filter_exp[] = "(dst port 53) and (udp[0xa] & 0x78 = 0x28)";
struct bpf_program fp; /* compiled filter program (expression) */
bpf_u_int32 mask; /* subnet mask */
bpf_u_int32 net; /* ip */
printf("%s","startPacketProcess called\n");
printf("Device sent to startPacketProcess: %s\n", dev);
/* get network number and mask associated with capture device */
if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1) {
fprintf(stderr, "Couldn't get netmask for device %s: %s\n",
dev, errbuf);
net = 0;
mask = 0;
}
/* open capture device */
handle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
if (handle == NULL) {
fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
exit(EXIT_FAILURE);
}
/* make sure we're capturing on an Ethernet device [2] */
if (pcap_datalink(handle) != DLT_EN10MB) {
fprintf(stderr, "%s is not an Ethernet\n", dev);
exit(EXIT_FAILURE);
}
/* compile the filter expression */
if (pcap_compile(handle, &fp, filter_exp, 0, net) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n",
filter_exp, pcap_geterr(handle));
ex开发者_运维问答it(EXIT_FAILURE);
}
/* apply the compiled filter */
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
pcap_freecode(&fp);
/* now we can set our callback function */
pcap_loop(handle, -1, process_packet, NULL);
printf("%s","End startPacketProcess call\n");
}
However, when I make a call to this function within my for loop it is only able to capture on one device since it seems to get stuck in the pcap_loop callback function. As a result of this I tried to do multi threading and the for loop that I use to pass in all the devices to open and capture to goes through the loop, but the pcap_loop callback function does not seem to execute. The following code shows my use of multi threading:
for (i = 0; i < numDevice; i++){
printf("Device returned by getDevices call: %s\n", deviceList[i]);
printf("%s","Entering for loop\n");
pthread_create(&tid, thAttr, startPacketProcess,(void*)deviceList[i]);
}
Does anyone know what I am doing wrong and can you provide me with suggestions on how to resolve this issue?
Thanks, Linh
process_packet
might be the problem. Try getting the packet in the thread context.
struct pcap_pkthdr *pkt_header;
u_char *pkt_data;
while ((retval = pcap_next_ex(mpPcap, &pkt_header, (const u_char **) &pkt_data)) >= 0) {
//Do Whatever
}
Have you tried using pcap_findalldevs()
or pcap_findalldevs_ex()
精彩评论