gpt4 book ai didi

c++ - 如何使 libpcap/pcap_loop 成为非阻塞的?

转载 作者:太空狗 更新时间:2023-10-29 21:17:56 45 4
gpt4 key购买 nike

我目前正在使用 libpcap 以混杂模式嗅探流量

int main() 
{
// some stuff
printf("Opening device: %s\n", devname.c_str());

handle = pcap_open_live(devname.c_str(), 65536 , 1 , 0 , errbuf);

if (handle == NULL)
{
fprintf(stderr, "Couldn't open device %s : %s..." , devname.c_str(), errbuf);
return 1;
}
printf(" Done\n");

pcap_loop(handle , -1 , process_packet , NULL);
// here run a thread to do some stuff. however, pcap_loop is blocking
return 0;
}

我想添加一个外部线程来做一些其他的事情。如何更改上面的代码以使其成为非阻塞的?

最佳答案

当你在 libpcap 上使用非阻塞模式时,你必须使用 pcap_dispatch,但是注意,pcap_dispatch 可以工作在阻塞或非阻塞模式,这取决于你如何设置 libpcap,设置 libpcap要以非阻塞方式工作,您必须使用函数 pcap_setnonblock:

int pcap_setnonblock(pcap_t *p, int nonblock, char *errbuf);

阻塞和非阻塞的区别不是循环永远运行,而是在阻塞函数pcap_dispatch等待一个数据包,只有收到这个数据包才返回,然而,在非-阻塞模式函数立即返回,回调必须处理数据包。

In "non-blocking" mode, an attempt to read from the capture descriptor with pcap_dispatch() will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive. pcap_loop() and pcap_next() will not work in "non-blocking" mode.

http://www.tcpdump.org/manpages/pcap_setnonblock.3pcap.html

关于c++ - 如何使 libpcap/pcap_loop 成为非阻塞的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31305712/

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