当您执行以下操作时,这将是一个问题:
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
。问题是google
andyoutube
指向同一个位置(从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