Search code examples
cmultithreadingpthreadslibpcappacket-sniffers

packet handlers in different threads in pcap


I'm trying to work with pcap and want it to work in a way wherein once I receive a packet, I want that packet to be processed independently while my pcap_loop() stills sniffs on other incoming packets.

This way I have my packet being processed and wait for an ACK for a specified time. If I don't receive an ACK, I take some other action.

What I don't understand is how to create a thread for a packet after it is sniffed..so that each packet is processed independently of the other.

So it would be something of this sort,

    pcap_loop(handle, -1, got_packet, NULL)

When creating a pthread where should I have my have my code for

    pthread_create(pthread_t, NULL, &got_packet, NULL)

Thanks for your help!

The following code below just captures one packet and then exits.

EDited to include code frags:

struct parameter {
    u_char *param1;
    const struct pcap_pkthdr *param2;
    u_char *param3;
};

pcap_loop(handle, -1, create_thread, NULL);

void create_thread(u_char *args, const struct pcap_pkthdr *header, u_char *packet)
{
 struct parameter thrd_args;
 thrd_args.param1 = args;
 thrd_args.param2 = header;
 thrd_args.param3 = packet;

 pthread_t packet_handler;

 pthread_create(&packet_handler, NULL, &got_packet, (void *)&thrd_args);
 error handling....
 pthread_exit(NULL);

}

void *got_packet(void *thrd_args)
{
struct parameters *thread_args;
thread_args = thrd_args;

u_char *args = &thread_args->param1;
const struct pcap_pkthdr *header = &thread_args->param2;
u_char *packet = &thread_args->param3;

}

Solution

  • Is there a real good reason for you to handle the packet processing in a different thread? The pcap driver stores packets for you in a queue so you will not miss them if they arrive while you process previous packets (depending of course on the size of the buffer you stated when you created the sniffer). Be that as it may, you should probably create the thread in your got_packet function (which will be called by the pcap driver every time a packet is sniffed) and give it the address of a different processing function like so: pthread_create(pthread_t, NULL, &process_packet, NULL) . Of course you need to somehow pass the packet to your new processing thread, but I'll leave that for you to figure out.