gethostbyname() only returns the address of local host on linux
I'm trying to portably (Windows & Linux) find all of the IP addresses of the local machine. The method I am using is to first call gethostname(), and then pass the result of that to gethostbyname(), whic开发者_Python百科h returns an array of ip addresses.
The problem is that on linux, the only address I get back is 127.0.0.1. This works on Windows, and I've seen a few people state that this will not work on Linux if your network was configured by DHCP (don't know if that's a true statement).
Is this not the correct way to do this on Linux?
It is not the correct way on unix/linux. The correct way involves ioctls to pull the necessary information.
struct ifreq ifc_buffer[MAX_NUM_IFREQ];
ioctl(s, SIOCGIFCONF, &ifc) # Interface list
num_ifreq = ifc.ifc_len / sizeof(struct ifreq);
for(cnt=0;cnt<num_ifreq;cnt++)
struct ifreq *ifr = &ifc.ifc_req[cnt]
ioctl(s, SIOCGIFADDR, ifr); # get ip address
There are also more modern methods involving:
if_nameindex()
Doing a SO search for if_nameindex and SIOCGIFCONF will yield a number of questions similar to this one.
This happens because on most distributions you have this in /etc/hosts
:
127.0.0.1 localhost.localdomain localhost aiur
gethostbyname
simply resolves the hostname (aiure
in this example) to an address. If it finds it in /etc/hosts
it's more than happy to give you that.
Back to the question. Unfortunately I don't believe you can get all the addresses of your machine in a portable way. You can do it in a Unix-portable way, like ifconfig
does. Open a socket s
and do an ioctl(..., SIOCGIFCONF, ...)
.
By the way, gethostbyname
is obsolete if you believe kernel.org and deprecated if you believe MSDN.
精彩评论