gpt4 book ai didi

c - 在 libpcap pcap_loop() 回调上传递参数

转载 作者:太空狗 更新时间:2023-10-29 15:00:00 28 4
gpt4 key购买 nike

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

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.

因此,据此,可以使用 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(带有配置结构数组)吗?

非常感谢您的帮助。

问候

最佳答案

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

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

关于c - 在 libpcap pcap_loop() 回调上传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1734507/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com