最近发现很多小伙伴在自学Linux网络编程这本书,中间可能会有许多不解的疑惑,书上有些地方讲解的也不是很透彻,恰巧之前选修过这门课,今天分享一个遇到的问题。
首先请看书的229页,8.4.4 函数gethostbyname不可重入的例子
先看下这段代码:
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct hostent *ht=NULL;
char host[]="www.sina.com.cn"; /*查询sina的主机域名*/
char host1[]="www.sohu.com"; /*查询sohu的主机域名*/
char str[30];
struct hostent *ht1=NULL, *ht2=NULL;
ht1 = gethostbyname(host); /*查询"www.sina.com.cn"*/
ht2 = gethostbyname(host1); /*查询"www.sohu.com"*/
int j = 0;
for(j = 0;j<2;j++){
if(j == 0)
ht = ht1; /*sina*/
else
ht =ht2; /*sohu*/
if(ht){
int i = 0;
printf("get the host:%s addr\n",host); /*原始域名*/
printf("name:%s\n",ht->h_name); /*名称*/
/*协议族AF_INET为IPv4或者AF_INET6为IPv6*/
printf("type:%s\n",ht->h_addrtype==AF_INET?"AF_INET":"AF_INET6");
printf("legnth:%

本文通过实例解析了Linux网络编程中gethostbyname函数的工作原理,解释了该函数如何导致两次查询结果混同的原因,并提供了代码示例。
最低0.47元/天 解锁文章
1332

被折叠的 条评论
为什么被折叠?



