tags:

views:

52

answers:

1

Hi,

I would like to create a array of in_addr using gethostbyname(). After looking on Google, I have found this short code (at http://www.logix.cz/michal/devel/various/gethostbyname.c.xp):

/*
 * gethostbyname.c - Example of using gethostbyname(3)
 * Martin Vidner <[email protected]>
 */

#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>

struct hostent *he;
struct in_addr a;

int
main (int argc, char **argv)
{
    if (argc != 2)
    {
        fprintf(stderr, "usage: %s hostname\n", argv[0]);
        return 1;
    }
    he = gethostbyname (argv[1]);
    if (he)
    {
        printf("name: %s\n", he->h_name);
        while (*he->h_aliases)
            printf("alias: %s\n", *he->h_aliases++);
        while (*he->h_addr_list)
        {
            bcopy(*he->h_addr_list++, (char *) &a, sizeof(a));
            printf("address: %s\n", inet_ntoa(a));
        }
    }
    else
        herror(argv[0]);
    return 0;
}

I tested this code with this:

$ ./a.out google.com
name: google.com
address: 74.125.45.100
address: 74.125.53.100
address: 74.125.67.100

Seeing this result, I am satisfied because I wanted a list of IP addresses from a domain.

But I just have one problem: I don't know how to save this list of IP addresses in a array (with the same size than addresses number)... have you got an example by chance?

Thank you

+1  A: 

The hostentry structure already provides the list of IP addresses as an array (MSDN). In your code example it is called he->h_addr_list, however the walking of it using *he->h_addr_list++ is losing your reference to it.

If you want to copy the array you'll need to work out how big it is and then malloc some memory to store it, then memcpy the array across.

Andrew Johnson