使用gethostbyname时分遇到的莫名其妙的输出

使用gethostbyname时候遇到的莫名其妙的输出
直接上代码(代码摘自unp卷1第十一章):

#include "myunp.h"

int main( int argc, char **argv )
{
char *ptr, **pptr;
char str[ INET_ADDRSTRLEN ];
struct hostent *hptr;

while ( --argc > 0 ){
ptr = *++argv;
if ( ( hptr = gethostbyname( ptr ) ) == NULL ){
printf("gethostbyname error for host:%s:%s\n", ptr, hstrerror( h_errno ) );
continue;
}
printf("official hostname:%s\n", hptr->h_name );
for ( pptr = hptr->h_aliases; *pptr != NULL; pptr++ )
printf("\talias:%s\n", *pptr );
switch( hptr->h_addrtype ){
case AF_INET:
pptr = hptr->h_addr_list;
for ( ; *pptr != NULL; pptr++ )
printf("\taddress:%s\n", *pptr );
// printf("\taddress:%s\n", inet_ntop( hptr->h_addrtype, *pptr, str, sizeof(str)));
break;
default:
printf("unknown address type");
break;
}
}

exit(0);
}


而程序输出:

root@ThinkPad-T430i:/home/leichaojian# ./hostent www.baidu.com
official hostname:www.baidu.com
address:(这里是乱码字符,CSDN不允许显示)a!kwww.(这里是乱码字符,CSDN不允许显示)a!lu.com
address:(这里是乱码字符,CSDN不允许显示)a!lu.com


所以,使用inet_ntop函数(我已经注释掉了)的时候,直接报异常错误了。这到底是为什么呢?
------解决思路----------------------
h_addr_list is really an array of struct in_add in disguise...

So, in order to access this array that appears to be char**, you should do:


addr_list = (struct in_addr **)he->h_addr_list;
 for(i = 0; addr_list[i] != NULL; i++) {
        printf("%s ", inet_ntoa(*addr_list[i]));
    }


As gethostbyname man page indicates, it points to the network addresses for the host (in network byte order)