Salvatorelab
Salvatorelab

Reputation: 11873

100% cpu usage with a libpcap simple example

while running the code below, one of the CPU cores reaches 100% usage. With or without traffic. What is wrong?

Example code:

#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <errno.h>

void my_callback(u_char *args, const struct pcap_pkthdr* pkthdr, const u_char*
packet)
{
    //nothing, nothing at all...
    //printf("+");
}

int main(int argc,char **argv)
{
    int i;
    char *dev;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    const u_char *packet;
    struct bpf_program fp;        /* hold compiled program */
    bpf_u_int32 maskp;            /* subnet mask */
    bpf_u_int32 netp;             /* ip */

    if(argc != 2){
        fprintf(stdout, "Usage: %s \"expression\"\n"
            ,argv[0]);
        return 0;
    }

    /* Now get a device */
    dev = pcap_lookupdev(errbuf);

    if(dev == NULL) {
        fprintf(stderr, "%s\n", errbuf);
        exit(1);
    }
    /* Get the network address and mask */
    pcap_lookupnet(dev, &netp, &maskp, errbuf);
    /* open device for reading in promiscuous mode */
    descr = pcap_open_live(dev, BUFSIZ, 1,-1, errbuf);
    if(descr == NULL) {
        printf("pcap_open_live(): %s\n", errbuf);
        exit(1);
    }

    /* Now we'll compile the filter expression*/
    if(pcap_compile(descr, &fp, argv[1], 0, netp) == -1) {
        fprintf(stderr, "Error calling pcap_compile\n");
        exit(1);
    }

    /* set the filter */
    if(pcap_setfilter(descr, &fp) == -1) {
        fprintf(stderr, "Error setting filter\n");
        exit(1);
    }

    /* loop for callback function */
    pcap_loop(descr, -1, my_callback, NULL);
    return 0;
}

compile with: gcc example.c -o example -lpcap

run with: ./example "tcp" or the filter you like.

As you can see it is the typical example, the main and the callback function for the loop: pcap_loop(descr, -1, my_callback, NULL);

The callback is empty (useless) but it is just to show that the problem is not in the callback.

Upvotes: 7

Views: 3078

Answers (1)

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

You specified timeout -1 here:

descr = pcap_open_live(dev, BUFSIZ, 1,-1, errbuf);

It turns pcap_loop into a busy loop, as poll continuously times out instantly.

Use something like 1000 (milliseconds) if you have no reason for other value.

Upvotes: 7

Related Questions