所以我用 #include <pcap.h>
解决了这个问题我得到的错误是错误 122,我会尽快解释错误 122。
这是代码。 请记住,这不是我的代码;我使用这段代码来说明发生了什么错误
#include <iostream>
#include <pcap/pcap.h>
#include <Windows.h>
using namespace std;
static int packetCount = 0;
void packetHandler(u_char *userData, const struct pcap_pkthdr* pkthdr, const u_char* packet) {
cout << ++packetCount << " packet(s) captured" << endl;
}
int main() {
char *dev;
pcap_t *descr;
char errbuf[PCAP_ERRBUF_SIZE];
dev = pcap_lookupdev(errbuf);
if (dev == NULL) {
cout << "pcap_lookupdev() failed: " << errbuf << endl;
system("pause");
return 1;
}
descr = pcap_open_live(dev, BUFSIZ, 0, -1, errbuf);
if (descr == NULL) {
cout << "pcap_open_live() failed: " << errbuf << endl;
system("pause");
return 1;
}
if (pcap_loop(descr, 10, packetHandler, NULL) < 0) {
cout << "pcap_loop() failed: " << pcap_geterr(descr);
system("pause");
return 1;
}
cout << "capture finished" << endl;
system("pause");
return 0;
}
现在,一旦我编译并运行,这就是我得到的 error
:
pcap_lookupdev() failed: PacketGetAdapterNames: The data area passed to a system call is too small. (122) Press any key to continue . . .
我用谷歌搜索了与我发布的问题(您正在阅读的那个)类似的问题,但它们似乎都在 Linux 中。 error
与 Admin 有关
特权。但我不知道如何实现这一点,我以 Admin
运行程序
我得到了这个(猜猜这是什么错误):
pcap_lookupdev() failed: PacketGetAdapterNames: The data area passed to a system call is too small. (122) Press any key to continue . . .
同error
:(
我了解 error
但我现在不知道如何阻止它。这error
被称为error 122
我还包括了Windows.h
只为 system("pause")
,所以不用担心,如果我有语法错误,也很抱歉。
最佳答案
我提议改进您的源代码,如下所示:
- 使用
pcap_findalldevs
查找所有现有设备。 alldevs
是一个链表,包含所有查找到的设备的首地址。/* 打印列表 */
部分,打印一个设备并获取下一个设备等等。
查找和打印设备:
pcap_if_t *alldevs, *d;
pcap_t *fp;
int i = 0;
u_int inum;
if (pcap_findalldevs(&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("%d", &inum);
if(inum < 1 || inum > i)
{
printf("\nInterface number out of range.\n");
/* Free the device list */
pcap_freealldevs(alldevs);
return -1;
}
最终以 live
打开设备并继续编码:
/* Jump to the selected adapter */
for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++);
/* Open the device */
if ( (fp= pcap_open_live(d->name, 100, 1, 20, errbuf) ) == NULL)
{
fprintf(stderr,"\nError opening adapter\n");
return -1;
}
这样,你就可以任意选择一个设备了。试试这个方法,看看有没有错误?
关于c++ - pcap_lookupdev 总是返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083431/