Passing an argument on libpcap pcap_loop() callback

落花浮王杯 提交于 2019-12-12 11:08:56

问题


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:


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);



回答2:


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);
}



回答3:


To compile the above code.

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

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



来源:https://stackoverflow.com/questions/1734507/passing-an-argument-on-libpcap-pcap-loop-callback

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!