在libpcap pcap_loop()回调上传递一个参数

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

pcap_loop()的原型如下:

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

最后一个参数在某些应用程序中很有用,但很多时候只是设置为NULL。 假设我们有自己的参数,我们希望发送到我们的回调函数,以及pcap_loop()发送的参数。 这就是我们这样做的地方。 显然,你必须对u_char指针进行类型转换,以确保结果正确地存在; 正如我们稍后将看到的,pcap使用了一些非常有趣的方法来以u_char指针的forms传递信息。

因此,根据这个,可以使用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); } 

经过一些测试我得到这种错误:

 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 '->' 

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

非常感谢任何帮助。

问候

你需要在main()之外定义结构,并在got_packet()中定义cast args ,如:

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

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

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

编译上面的代码。

安装libpcap – > sudo apt-get install libpcap0.8-dev

然后 – > gcc got_packet.c -lpcap -o got_packet.o