从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: %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的正式主机名是www.google.com
而不是youtube-ui.l.google.com。问题是googleyoutube
指向同一位置(从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

所以只要处理第一个hostentgethostbyname指针
在你打第二个电话之前打电话,你会没事的。

关于c - 什么时候多次调用gethostbyname是不安全的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49758873/

10-10 19:41