c - 何时多次调用gethostbyname是不安全的



From 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的多次调用会覆盖此静态数据时?

当你做这样的事情时,这将是一个问题:

struct hostent *google = gethostbyname("www.google.com");
struct hostent *youtube = gethostbyname("www.youtube.com");
printf("Official name of host for www.google.com: %sn", google->h_name);
printf("Official name of host for www.youtube.com: %sn", youtube->h_name);
printf("same? %sn", 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的官方主机名是www.google.com而不是youtube-ui.l.google.com.问题是googleyoutube指向同一位置(从same? yes输出中可以看到(,因此,当您再次执行gethostbyname时,有关www.google.com的信息会丢失。

但是,如果您这样做

struct hostent *google = gethostbyname("www.google.com");
printf("Official name of host for www.google.com: %sn", google->h_name);
struct hostent *youtube = gethostbyname("www.youtube.com");
printf("Official name of host for www.youtube.com: %sn", 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在你做第二个电话之前打电话,你会没事的。

struct hostent *host1 = gethostbyname("host1");
struct hostent *host2 = gethostbyname("host2");
if(host1......)

第二个调用覆盖了(可能(第一个调用的结果

下面是一个示例:

struct hostent *he1 = gethostbyname("host1");
struct in_addr *addr1 = (struct in_addr *)(he1->h_addr);
printf("addr1=%sn", inet_ntoa(*addr1));    // prints IP1
struct hostent *he2 = gethostbyname("host2");
struct in_addr *addr2 = (struct in_addr *)(he2->h_addr);
printf("addr2=%sn", inet_ntoa(*addr2));    // prints IP2
printf("addr1=%sn", inet_ntoa(*addr1));    // prints IP1 (!)

相关内容

  • 没有找到相关文章

最新更新