gpt4 book ai didi

c++ - 无法使用 pcap_findalldevs 获取 ip 地址

转载 作者:搜寻专家 更新时间:2023-10-31 00:14:08 26 4
gpt4 key购买 nike

我正在使用 pcap_findalldevs 获取计算机中的设备列表。我成功地获得了它,包括设备名称和描述,但我不知道为什么,我得到的网络掩码是 0.0.0.0,IP 地址也是 0.0.0.0。这是我生成列表的代码:

/* get the devices list */
if (pcap_findalldevs(&devList, errbuf) == -1)
{
fprintf(stderr, "There is a problem with pcap_findalldevs: %s\n", errbuf);
return -1;
}

/* scan the list for a suitable device to capture from */
for (dev = devList; dev != NULL; dev = dev->next)
{

pcap_addr_t *dev_addr; //interface address that used by pcap_findalldevs()

/* check if the device captureble*/
if ((dev_addr = dev->addresses) != NULL && dev_addr->addr->sa_family == AF_INET && dev_addr->addr && dev_addr->netmask) {
printf("Found a device %s on address %s with netmask %s\n", dev->name, iptos(((struct sockaddr_in *)dev_addr->addr)->sin_addr.s_addr), iptos(((struct sockaddr_in *)dev_addr->netmask)->sin_addr.s_addr));
break;
}
}

最佳答案

这是您应该做的:

/* get the devices list */
if (pcap_findalldevs(&devList, errbuf) == -1)
{
fprintf(stderr, "There is a problem with pcap_findalldevs: %s\n", errbuf);
return -1;
}

/* scan the list for a suitable device to capture from */
for (dev = devList; dev != NULL; dev = dev->next)
{

pcap_addr_t *dev_addr; //interface address that used by pcap_findalldevs()

/* check if the device captureble*/
for (dev_addr = dev->addresses; dev_addr != NULL; dev_addr = dev_addr->next) {
if (dev_addr->addr->sa_family == AF_INET && dev_addr->addr && dev_addr->netmask) {
printf("Found a device %s on address %s with netmask %s\n", dev->name, iptos(((struct sockaddr_in *)dev_addr->addr)->sin_addr.s_addr), iptos(((struct sockaddr_in *)dev_addr->netmask)->sin_addr.s_addr));
goto found;
}
}
}

found:

这样,您就可以检查整个 地址列表,而不仅仅是列表中的第一个地址。如果,当你到达found时,dev是非空的,它指向一个至少有一个IPv4地址的设备,而dev_addr指向那个地址。如果 dev 为 null,则没有具有 IPv4 地址的设备。

关于c++ - 无法使用 pcap_findalldevs 获取 ip 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24270541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com