Any given computer will have one or more associated ip addresses. When you call gethostbyname(), you validate the pointer, then access it's char * h_addr_list[], cycling though till a null pointer is reached. During each of those iterations, you will cast that index's char * to an unsigned long *, dereference that pointer to get each available address (which is in network byte order).
OK, so I don't explain very clearly so I will resort to an example.
Code:
/* get_ips() returns the number of addresses copied to addr_buff.
Optionally, you can pass a pointer the count as the last parameter. */
int get_ips(const char * hostname, unsigned long addr_buff[], int max, int * count = 0)
{
int index = 0;
if(count == 0) count = &index;
hostent * host = gethostbyname(hostname);
if(!host && max != 0)
{
if((addr_buff[index] = inet_addr(hostname)) != INADDR_NONE)
++index;
}
else
{
for( ; host->h_addr_list[ index ] && index < max; ++index )
{
addr_buff[index] = ( *(unsigned long*)host->h_addr_list[ index ] );
}
}
return *count = index;
}
int local_host(unsigned long addr_buff[], int max, int * count = 0)
{
const int buff_size = 10240;
char local[buff_size];
gethostname(local, buff_size);
return get_ips(local, addr_buff, max, count);
}
Of course, any variation off that basic theme will do.
Here's a basic program:
Code:
int main()
{
const int max = 246; // *just in case* :p
unsigned long addresses[max];
int total = local_host(addresses, max);
cout << "There are " << total << " addresses available." << endl
<< "The are:" << endl;
for(int index = 0; index < total; ++index)
cout << inet_ntoa(addresses[index]) << endl;
return cin.get();
}
Happy coding.