0

来自 gethostbyname(3) - Linux 手册

The functions gethostbyname() and gethostbyaddr() may return pointers
to static data, which may be overwritten by later calls.  Copying the
struct hostent does not suffice, since it contains pointers; a deep
copy is required.

我编写的程序可以多次调用gethostbyname并且由于覆盖静态数据而没有任何中断。

gethostbyname当多次调用会覆盖这个静态数据时,我可以问一个例子吗?

4

3 回答 3

2

当您执行以下操作时,这将是一个问题:

struct hostent *google = gethostbyname("www.google.com");
struct hostent *youtube = gethostbyname("www.youtube.com");

printf("Official name of host for www.google.com: %s\n", google->h_name);
printf("Official name of host for www.youtube.com: %s\n", youtube->h_name);

printf("same? %s\n", google == youtube ? "yes" : "no");

输出将是

Official name of host for www.google.com: youtube-ui.l.google.com
Official name of host for www.youtube.com: youtube-ui.l.google.com
same? yes

www.google.com这是错误的,因为iswww.google.com 和 not的官方主机名youtube-ui.l.google.com。问题是googleandyoutube 指向同一个位置(从same? yes输出中可以看到),所以当你再次执行时,关于的信息www.google.com会丢失gethostbyname

如果你这样做

struct hostent *google = gethostbyname("www.google.com");
printf("Official name of host for www.google.com: %s\n", google->h_name);

struct hostent *youtube = gethostbyname("www.youtube.com");
printf("Official name of host for www.youtube.com: %s\n", youtube->h_name);

那么输出将是

Official name of host for www.google.com: www.google.com
Official name of host for www.youtube.com: youtube-ui.l.google.com

因此,只要 在进行第二次调用之前处理hostent第一次调用的指针,就可以了。gethostbyname

于 2018-04-10T16:47:38.253 回答
1
struct hostent *host1 = gethostbyname("host1");
struct hostent *host2 = gethostbyname("host2");

if(host1......)

第二次调用已覆盖(可能)第一次调用的结果

于 2018-04-10T16:46:12.407 回答
1

这是一个例子:

struct hostent *he1 = gethostbyname("host1");
struct in_addr *addr1 = (struct in_addr *)(he1->h_addr);

printf("addr1=%s\n", inet_ntoa(*addr1));    // prints IP1

struct hostent *he2 = gethostbyname("host2");
struct in_addr *addr2 = (struct in_addr *)(he2->h_addr);

printf("addr2=%s\n", inet_ntoa(*addr2));    // prints IP2

printf("addr1=%s\n", inet_ntoa(*addr1));    // prints IP1 (!)
于 2018-04-10T16:48:31.463 回答