我在使用libpcap函数“ pcap_findalldevs”时遇到问题。问题是当我运行代码时给出了“分段错误”。代码是:
int listDevices()
{
int res = -1;
int count = 1;
pcap_if_t *device;
pcap_if_t **alldev;
char e_buffer[PCAP_ERRBUF_SIZE];
res = pcap_findalldevs(alldev, e_buffer); //Gives "segmentation fault" here
if (res == 0)
{
printf("Error reading list of devices: %s\n", e_buffer);
return res;
}
if (alldev == NULL)
{
printf("No devices founded!");
return 1;
}
device = *alldev;
while(device != NULL)
{
printf("%s\n", device->name);
device= device->next;
}
pcap_freealldevs(*alldev);
return 0;
}
[观察变量,我可以看到** alldev给的地址为0x0,而其他的则为“普通”地址。我在做什么错?
谢谢你。
res = pcap_findalldevs(alldev, e_buffer);
您在这里没有给alldev
一个值,因此它向pcap_findalldevs()
传递了一个随机值,导致它崩溃。
需要传递给pcap_findalldevs()
的是指向pcap_if_t
变量的指针,所以应该这样做
res = pcap_findalldevs(&device, e_buffer);
如果该调用返回的值不是PCAP_ERROR
,则将device
设置为指向pcap_if_t
结构列表的第一个元素-或为NULL(如果未找到接口)。也就是说,返回值0表示成功,因此您应该这样做
if (res == PCAP_ERROR)
{
printf("Error reading list of devices: %s\n", e_buffer);
return res;
}
作为错误检查。
您可以摆脱alldev
变量。