3

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(), which 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?

dicroce
  • 45,396
  • 28
  • 101
  • 140

2 Answers2

1

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.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
1

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.

Seth Robertson
  • 30,608
  • 7
  • 64
  • 57