捕获数据包而没有回调
本课程中的示例程序与以前的程序(打开适配器和捕获数据包)完全相同,但它使用pcap_next_ex()而不是pcap_loop()。
pcap_loop()的基于回调的捕获机制是优雅的,在某些情况下可能是一个很好的选择。
但是,处理回调有时是不实际的 - 通常会使程序更加复杂,特别是在多线程应用程序或C ++类的情况下。
在这些情况下,pcap_next_ex()使用直接调用检索数据包 - 只有在程序员想要的时候才使用pcap_next_ex()数据包。
该函数的参数与捕获回调相同 - 它需要一个适配器描述符和一些将被初始化并返回给用户的指针(一个到pcap_pkthdr结构,另一个指向具有数据包数据的缓冲区)。
在以下程序中,我们回收上一课程示例的回调代码,并在调用pcap_next_ex()之后将其移动到main()中。
#include "pcap.h"
int main()
{
pcap_if_t *alldevs;
pcap_if_t *d;
int inum;
int i=0;
pcap_t *adhandle;
int res;
char errbuf[PCAP_ERRBUF_SIZE];
struct tm ltime;
char timestr[16];
struct pcap_pkthdr *header;
const u_char *pkt_data;
time_t local_tv_sec;
/* Retrieve the device list on the local machine */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf);
exit(1);
}
/* Print the list */
for(d=alldevs; d; d=d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if(i==0)
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\n");
return -1;
}
printf("Enter the interface number (1-%d):",i);
scanf_s("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (adhandle= pcap_open(d->name, // name of the device
65536, // portion of the packet to capture.
// 65536 guarantees that the whole packet will be captured on all the link layers
PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode
1000, // read timeout
NULL, // authentication on the remote machine
errbuf // error buffer
) ) == NULL)
{
fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name);
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
printf("\nlistening on %s...\n", d->description);
/* At this point, we don't need any more the device list. Free it */
pcap_freealldevs(alldevs);
/* Retrieve the packets */
while((res = pcap_next_ex( adhandle, &header, &pkt_data)) >= 0){
if(res == 0)
/* Timeout elapsed */
continue;
/* convert the timestamp to readable format */
local_tv_sec = header->ts.tv_sec;
localtime_s(<ime, &local_tv_sec);
strftime( timestr, sizeof timestr, "%H:%M:%S", <ime);
printf("%s,%.6d len:%d\n", timestr, header->ts.tv_usec, header->len);
}
if(res == -1){
printf("Error reading the packets: %s\n", pcap_geterr(adhandle));
return -1;
}
return 0;
}
为什么我们使用pcap_next_ex()而不是旧的pcap_next()?因为pcap_next()有一些缺点。首先,它是低效的,因为它隐藏回调方法,但仍依赖于pcap_dispatch()。第二,它不能检测到EOF,所以在从文件中收集数据包时不是很有用。
还要注意,pcap_next_ex()返回成功,超时时间,错误和EOF条件的不同值。