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

fzyz_sb 2014-09-22 09:54:26
直接上代码(代码摘自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函数(我已经注释掉了)的时候,直接报异常错误了。这到底是为什么呢?
...全文
142 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
fzyz_sb 2014-09-23
  • 打赏
  • 举报
回复
引用 1 楼 micropentium6 的回复:
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)
你说的很正确。但是不知道为什么我的ubuntu系统上就是报错。我甚至找了网上的代码运行也是出错,搞不懂为什么,书上的代码应该也是正确的,你说的也是正确的,我也大概理解了。不过谢谢你,希望有一天我的编程能达到你的高度。
  • 打赏
  • 举报
回复
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)

23,216

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧