Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an argument on libpcap pcap_loop() callback

Tags:

c

libpcap

Because I would like to make some tests with the libpcap and a small C program, I am trying to pass a structure from main() to got_packet(). After reading the libpcap tutorial, I had found this:

The prototype for pcap_loop() is below:

int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)

The last argument is useful in some applications, but many times is simply set as NULL. Suppose we have arguments of our own that we wish to send to our callback function, in addition to the arguments that pcap_loop() sends. This is where we do it. Obviously, you must typecast to a u_char pointer to ensure the results make it there correctly; as we will see later, pcap makes use of some very interesting means of passing information in the form of a u_char pointer.

So according to this, it is possible to send the structure in got_packet() using the argument number 4 of pcap_loop(). But after trying, I get an error.

Here is my (bugged) code:

int main(int argc, char **argv)
{
 /* some line of code, not important */

 /* def. of the structure: */
 typedef struct _configuration Configuration;
 struct _configuration {
   int id;
   char title[255];
 };

 /* init. of the structure: */
 Configuration conf[2] = {
   {0, "foo"},
   {1, "bar"}};

 /* use pcap_loop with got_packet callback: */
 pcap_loop(handle, num_packets, got_packet, &conf);
}

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
 /* this line don't work: */
 printf("test: %d\n", *args[0]->id);
}

I get this kind of error after some tests:

gcc -c got_packet.c -o got_packet.o
got_packet.c: In function ‘got_packet’:
got_packet.c:25: error: invalid type argument of ‘->’

Do you see how can I edit this code in order to pass conf (with is a array of configuration structure) in got_packet() function?

Many thanks for any help.

Regards

like image 208
Denis Avatar asked Nov 14 '09 15:11

Denis


2 Answers

I rewrite Your code, it is now compile without any error:

#include <pcap.h> 

typedef struct {
  int id;
  char title[255];
} Configuration;

void got_packet( Configuration args[], const struct pcap_pkthdr *header, const u_char *packet){
  (void)header, (void)packet;
  printf("test: %d\n", args[0].id);
}

int main(void){
  Configuration conf[2] = {
    {0, "foo"},
    {1, "bar"}};

  pcap_loop(NULL, 0, (pcap_handler)got_packet, (u_char*)conf);
}
like image 114
sambowry Avatar answered Oct 18 '22 17:10

sambowry


You need to define the structure outside of main() and cast args in got_packet() like:

Configuration *conf = (Configuration *) args;
printf ("test: %d\n", conf[0].id);
like image 2
Gonzalo Avatar answered Oct 18 '22 19:10

Gonzalo