A friend used the following snippet of code to retrieve the local IP address of the host in his LAN.
int buffersize = 512;
char name[buffersize];
if(gethostname(name, buffersize) == -1){
Exception excep("Failed to retrieve the name of the computer");
excep.raise();
}
struct hostent *hp = gethostbyname(name);
if(hp == NULL){
Exception excep("Failed to retrieve the IP address of the local host");
excep.raise();
}
struct in_addr **addr_list = (struct in_addr **)hp->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++) {
qDebug() << QString(inet_ntoa(*addr_list[i]));
}
It appears to work fine on his Mac. He said that the last IP address in that array was the one he needed to know. However, I got these values on my Linux laptop...
127.0.0.2
192.168.5.1
1.2.3.0
These looks similar to the values used by my adapters, but not the same. Here's some ifconfig
data:
eth0 Link encap:Ethernet HWaddr 1C:C1:DE:91:54:1A
UP BROADCAST MULTICAST MTU:1500 Metric:1
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
wlan0 Link encap:Ethernet HWaddr [bleep]
inet addr:192.168.1.6 Bcast:192.168.1.255 Mask:255.255.255.0
It appears that some of the bits were scrambled. Are we missing a crucial conversion here?