Passing an argument in a libpcap pcap_loop () call

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

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 just set to NULL. Suppose we have arguments that we want to send to our callback functions, in addition to the arguments that pcap_loop () sends. This is where we do it. Obviously, you must typecast to the u_char pointer to ensure the results do it there correctly; as we will see later, pcap uses some very interesting means of transmitting information in the form of a u_char pointer.

Thus, in accordance with this, you can send the structure to got_packet () using argument number 4 pcap_loop (). But after trying, I get an error message.

Here is my (listened) 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 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 '->' 

You see how I can edit this code to pass conf (with an array of configuration structure) to get_packet ()?

Thanks so much for any help.

Hi

+4
source share
3 answers

You need to define a structure outside main () and cast args in get_packet (), for example:

 Configuration *conf = (Configuration *) args; printf ("test: %d\n", conf[0].id); 
+2
source

I am rewriting my code, now it compiles without errors:

 #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); } 
+4
source

Compile the above code.

install libpcap -> sudo apt-get install libpcap0.8-dev

then -> gcc got_packet.c -lpcap -o got_packet.o

+1
source

All Articles