c - pcap中不同线程中的数据包处理程序

标签 c multithreading pthreads libpcap packet-sniffers

我正在尝试使用 pcap 并希望它以一种方式工作,一旦我收到一个数据包,我希望该数据包被独立处理,而我的 pcap_loop() 仍然嗅探其他传入的数据包。

这样我就可以处理我的数据包并在指定的时间内等待 ACK。如果我没有收到 ACK,我会采取其他措施。

我不明白的是如何在数据包被嗅探后创建一个线程......以便每个数据包都独立于其他数据包进行处理。

所以它会是这样的,

    pcap_loop(handle, -1, got_packet, NULL)

当创建一个 pthread 时,我应该在哪里拥有我的代码

    pthread_create(pthread_t, NULL, &got_packet, NULL)

感谢您的帮助!

下面的代码只是捕获一个数据包然后退出。

编辑为包含代码片段:

struct parameter {
    u_char *param1;
    const struct pcap_pkthdr *param2;
    u_char *param3;
};

pcap_loop(handle, -1, create_thread, NULL);

void create_thread(u_char *args, const struct pcap_pkthdr *header, u_char *packet)
{
 struct parameter thrd_args;
 thrd_args.param1 = args;
 thrd_args.param2 = header;
 thrd_args.param3 = packet;

 pthread_t packet_handler;

 pthread_create(&packet_handler, NULL, &got_packet, (void *)&thrd_args);
 error handling....
 pthread_exit(NULL);

}

void *got_packet(void *thrd_args)
{
struct parameters *thread_args;
thread_args = thrd_args;

u_char *args = &thread_args->param1;
const struct pcap_pkthdr *header = &thread_args->param2;
u_char *packet = &thread_args->param3;

}

最佳答案

您有充分的理由在不同的线程中处理数据包吗? pcap 驱动程序为您将数据包存储在队列中,因此如果它们在您处理之前的数据包时到达,您就不会错过它们(当然取决于您在创建嗅探器时指定的缓冲区大小)。尽管如此,您应该在 got_packet 函数中创建线程(每次嗅探数据包时 pcap 驱动程序都会调用该线程)并为其提供不同处理函数的地址,如下所示: pthread_create( pthread_t, NULL, &process_packet, NULL) 。当然,您需要以某种方式将数据包传递给新的处理线程,但我会把它留给您自己解决。

关于c - pcap中不同线程中的数据包处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23603564/

相关文章:

c - 如何初始化数组并填充缓冲区中的字符?

java - Android 中的 java.util.Observable 是线程安全的吗?

c# - 通过 Web API 请求(用户 session )共享和更新静态集合

c - 为什么我会收到运行时错误

c - 如何改进我的代码以从文本表填充数组?

c - C 语言中可以并行执行输入/输出操作吗?

c - C中的 float 和 double

ios - NSOperationQueue,并发操作和线程

php - gdb 显示奇怪的无符号线程导致 SIGSEGV - 它是什么?

c - 在尝试运行 C pthread 程序的命令行中出现权限被拒绝错误