在libpcap pcap_loop()回调中传递参数

Den*_*nis 5 c libpcap

因为我想使用libpcap和一个小型C程序进行一些测试,所以我试图将结构从main()传递给got_packet()。阅读libpcap教程后,我发现了这一点:

pcap_loop()的原型如下:

int pcap_loop(pcap_t *p, int cnt, pcap_handler callback, u_char *user)
Run Code Online (Sandbox Code Playgroud)

最后一个参数在某些应用程序中很有用,但是很多时候只是将其设置为NULL。假设除了pcap_loop()发送的参数外,我们还有自己希望发送给回调函数的参数。这就是我们要做的。显然,您必须强制转换为u_char指针,以确保结果正确到达该指针。稍后我们将看到,pcap利用一些非常有趣的方式以u_char指针的形式传递信息。

因此,据此,可以使用pcap_loop()的参数编号4在got_packet()中发送结构。但是尝试之后,我得到了一个错误。

这是我的(错误的)代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

经过一些测试,我得到了这样的错误:

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 ‘->’
Run Code Online (Sandbox Code Playgroud)

您是否看到我该如何编辑此代码,以便在got_packet()函数中传递conf(带有配置结构数组)?

非常感谢您的帮助。

问候

sam*_*wry 5

我重写了你的代码,现在编译没有任何错误:

#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);
}
Run Code Online (Sandbox Code Playgroud)


Gon*_*alo 2

您需要在 main() 之外定义结构并在 got_packet() 中强制转换参数,如下所示:

Configuration *conf = (Configuration *) args;
printf ("test: %d\n", conf[0].id);
Run Code Online (Sandbox Code Playgroud)