我想使用 gethostbyname() 创建一个 in_addr 数组。在 Google 上查看后,我发现了这个简短的代码(在 http://www.logix.cz/michal/devel/various/gethostbyname.c.xp ):
/*
* gethostbyname.c - Example of using gethostbyname(3)
* Martin Vidner <mvidner@suse.cz>
*/
#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;
}
我用这个测试了这段代码:
$ ./a.out google.com
name: google.com
address: 74.125.45.100
address: 74.125.53.100
address: 74.125.67.100
看到这个结果,我很满意,因为我想要一个域中的 IP 地址列表。
但我只有一个问题:我不知道如何将这个 IP 地址列表保存在数组中(其大小与地址数相同)...您有机会提供一个示例吗?
谢谢
最佳答案
hostentry 结构已以数组形式提供 IP 地址列表 ( MSDN )。在您的代码示例中,它被称为 he->h_addr_list
,但是使用 *he->h_addr_list++
对其进行遍历会丢失对它的引用。
如果你想复制数组,你需要计算出它有多大,然后分配一些内存来存储它,然后对数组进行memcpy。
关于c - in_addr 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1804230/