一位朋友使用following snippet of code来检索其局域网中主机的本地IP地址。无法使用gethostbyname获取本地IP()
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]));
}
它似乎在他的Mac上正常工作。他表示,该阵列中的最后一个IP地址是他需要知道的。但是,我得到了我的Linux笔记本电脑这些价值观......
127.0.0.2
192.168.5.1
1.2.3.0
这些类似于通过我的适配器使用的值,但不一样的。下面是一些ifconfig
数据:
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
看来,一些位进行加扰。我们是否错过了这里的关键转换?
我在Windows上测试了你的代码(VS2010;所以没有使用Exception和QString),它返回的是IP地址的值。 –
也许我的主机保存某些数据的方式有所不同?我被告知,网络具有普遍认同的表示数据的方式,这就是为什么你必须在某些事情上进行“网络到主机”和“主机到网络”的转换。 – Pieter
'inet_ntoa'已被弃用,事实证明。但是接下来我该如何解码'addr_list'中的每个字符串,这些字符串按照网络字节顺序进行编码,然后返回到主机顺序?我在每个角色上尝试了'ntohs()',但是没有得到预期的结果。 – Pieter