gpt4 book ai didi

c - 多次调用 gethostbyname 什么时候不安全?

转载 作者:太空宇宙 更新时间:2023-11-04 06:14:07 24 4
gpt4 key购买 nike

来自 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 输出中看到的那样),因此,当您再次执行 gethostbyname 时,有关 www.google.com 的信息将丢失。

如果你这样做

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

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com