tags:

views:

172

answers:

2

Hi,

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

+1  A: 

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);
Gonzalo
Many thanks! Working perfectly!!!
Denis
+2  A: 

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);
}
sambowry
Awesome :) Thanks again!
Denis