开发者

how to timeout periodically in libpcap packet receiving functions

开发者 https://www.devze.com 2023-03-22 19:47 出处:网络
I found this post in stackoverflow.com listening using Pcap with timeout I am facing a similar (but different) problem: what is the GENERIC (platform-independent) method to timeout periodically when

I found this post in stackoverflow.com listening using Pcap with timeout

I am facing a similar (but different) problem: what is the GENERIC (platform-independent) method to timeout periodically when receiving captured packets by using libpca开发者_运维技巧p packet receiving functions? Actually, I am wondering if it is possible to periodically timeout from the pcap_dispatch(pcap_t...) / pcap_next_ex(pcap_t...)? If that is possible, I can use them just like using the classic select(...timeout) function ( http://linux.die.net/man/2/select ).

In addition, from the official webpage ( http://www.tcpdump.org/pcap3_man.html ), I found the original timeout mechanism is considered buggy and platform-specific (This is bad, since my program may run on different Linux and Unix boxes):

"... ... to_ms specifies the read timeout in milliseconds. The read timeout is used to arrange that the read not necessarily return immediately when a packet is seen, but that it wait for some amount of time to allow more packets to arrive and to read multiple packets from the OS kernel in one operation. Not all platforms support a read timeout; on platforms that don't, the read timeout is ignored ... ...

NOTE: when reading a live capture, pcap_dispatch() will not necessarily return when the read times out; on some platforms, the read timeout isn't supported, and, on other platforms, the timer doesn't start until at least one packet arrives. This means that the read timeout should NOT be used in, for example, an interactive application, to allow the packet capture loop to "poll" for user input periodically, as there's no guarantee that pcap_dispatch() will return after the timeout expires... ..."

Therefore, I guess I need to implement the GENERIC (platform-independent) timeout mechanism by myself like below?

  1. create a pcap_t structure with pcap_open_live().
  2. set it in nonblocking mode with pcap_setnonblock(pcap_t...).
  3. poll this nonblocking pcap_t with registered OS timer like:

register OS timer_x, and reset timer_x;

while(1) {

if(timer_x times out) {do something that need to be done periodically; reset timer_x;}

poll pcap_t by calling pcap_dispatch(pcap_t...)/pcap_next_ex(pcap_t...) to receive some packets;

do something with these packets;

}//end of while(1)

Regards,

DC


You can get the handle with pcap_fileno() and select() it. There's a sample here in OfferReceiver::Listen().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号