问题
Following example code from the libpcap documentation yields the following code which should report the IP address of the given interface (eth0 in this case) [Error checking omitted for brevity]
#include <stdio.h>
#include <pcap.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
char errbuf[PCAP_ERRBUF_SIZE];
bpf_u_int32 mask;
bpf_u_int32 ip;
struct in_addr ip_addr;
/* Find the properties for the device */
pcap_lookupnet("eth0", &ip, &mask, errbuf);
ip_addr.s_addr = ip;
printf("IP Address: %s\n", inet_ntoa(ip_addr));
return 0;
}
However, this results in 192.168.1.0, rather than the correct 192.168.1.100. Running this on a different machine on a different subnet yields 10.0.0.0 rather than the correct 10.0.0.107 which leads me to believe libpcap is not copying the last octet correctly. I've manually converted the integer returned by pcap_lookupnet to ensure it's not an issue with the use of inet_ntoa (I've also tried inet_ntop, with identical results). Following the code from this question: Get IP address of an interface on Linux reports the correct IP address. Is this a bug in libpcap or am I doing something wrong?
回答1:
Your statement "which should report the IP address of the given interface" is incorrect.
From the manpage:
pcap_lookupnet() is used to determine the IPv4 network number and mask associated with the network device device. Both netp and maskp are bpf_u_int32 pointers.
are you sure you have a network number of 10.0.0.107 or 192.168.1.100 respectively? Sounds rather unusual.
来源:https://stackoverflow.com/questions/9213828/pcap-lookupnet-returns-incorrect-ip-address