从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
。问题是google
和youtube
指向同一位置(从
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
指针在你打第二个电话之前打电话,你会没事的。
关于c - 什么时候多次调用gethostbyname是不安全的?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49758873/