我使用libpcap 1.5.3在openwrt中工作。
我有init pcap如下:
handle = pcap_create(capnic, errbuf);
if(!handle) {
sys_err("pcap_create failed:%s\n", errbuf);
exit(-1);
}
if(pcap_set_snaplen(handle, BUFSIZE)) {
sys_err("pcap_set_snaplen failed\n");
exit(-1);
}
if(pcap_activate(handle)) {
sys_err("pcap_activate failed: %s\n",
pcap_geterr(handle));
exit(-1);
}
并使用pcap_next
捕获数据包:
struct pcap_pkthdr hdr;
const u_char * sysbuf;
if(!(sysbuf = pcap_next(handle, &hdr))) {
sys_err("recv packet failed\n");
return 0;
}
该程序可以捕获数据包,但是有很多错误信息:
recv packet failed
我已使用函数pcap_getnonblock
检查了阻止状态,句柄为block
。
答案 0 :(得分:1)
引用我机器上的pcap_next()/ pcap_next_ex()手册页:
pcap_next_ex() returns 1 if the packet was read without problems, 0 if
packets are being read from a live capture, and the timeout expired, -1
if an error occurred while reading the packet, and -2 if packets are
being read from a ``savefile'', and there are no more packets to read
from the savefile. If -1 is returned, pcap_geterr() or pcap_perror()
may be called with p as an argument to fetch or display the error text.
pcap_next() returns a pointer to the packet data on success, and
returns NULL if an error occured, or if no packets were read from a
live capture (if, for example, they were discarded because they didn't
pass the packet filter, or if, on platforms that support a read timeout
that starts before any packets arrive, the timeout expires before any
packets arrive, or if the file descriptor for the capture device is in
non-blocking mode and no packets were available to be read), or if no
more packets are available in a ``savefile.'' Unfortunately, there is
no way to determine whether an error occured or not.
特别注意
pcap_next()
...如果发生错误,则返回NULL,*或者如果没有从实时捕获中读取数据包(例如,如果它们因为未通过数据包过滤器而被丢弃,或者如果,在支持在任何数据包到达之前启动的读取超时的平台上,超时在任何数据包到达之前到期......)
另请注意
不幸的是,无法确定是否发生错误。
这是手册页告诉您应该使用pcap_next_ex()
的方式, 区分这两种情况。