I just wrote this snippet:
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
int main(void)
{
sockaddr_in self;
hostent *he;
char local[HOST_NAME_MAX];
gethostname(local, sizeof(local));
he = gethostbyname(local);
if (he)
{
std::cout << "Addresses: " << std::endl;
unsigned int i = 0;
while(he->h_addr_list[i] != NULL)
{
std::cout << "\t" << i << " --> ";
memcpy(&self.sin_addr, he->h_addr_list[i], he->h_length);
std::cout << self.sin_addr.s_addr;
std::cout << " ( " << inet_ntoa( *( struct in_addr*)( he-> h_addr_list[i])) << " )" << std::endl;
i++;
}
}
else
std::cout << "gethostname failed" << std::endl;
}
When I run it on an example host I get something like this (i made up these addresses here though):
Addresses: 0 --> 1307150150 ( 10.23.215.61 )
whereas if I run ifconfig
I get much more outuput, and in particular the above address corresponds to only the first displayed interface from ifconfig
when there are at least two more before the eth0
ones. How come? I would have expected this to run through all of the possible network addresses in this host...
After the answer below, I did the following (using getaddrinfo):
int main(void)
{
struct addrinfo *result;
struct addrinfo *res;
int error;
char local[HOST_NAME_MAX];
gethostname(local, sizeof(local));
error = getaddrinfo(local, NULL, NULL, &result);
if (error != 0)
{
fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
return 1;
}
for (res = result; res != NULL; res = res->ai_next)
{
struct in_addr addr;
addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;
std::cout << addr.s_addr
<< " ("
<< inet_ntoa(addr)
<< " )"
<< std::endl;
}
freeaddrinfo(result);
}
I now get the same output as before..except repeated the "correct" number of times. (i.e. from ifconfig I see three interfaces from which I could presumably send from in multicast and I get the inet address of the first one repeated thrice as output of above.