当前位置: 技术问答>linux和unix
使用gethostbyname时候遇到的莫名其妙的输出
来源: 互联网 发布时间:2017-05-29
本文导语: 直接上代码(代码摘自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...
直接上代码(代码摘自unp卷1第十一章):
而程序输出:
所以,使用inet_ntop函数(我已经注释掉了)的时候,直接报异常错误了。这到底是为什么呢?
#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:%sn", ptr, hstrerror( h_errno ) );
continue;
}
printf("official hostname:%sn", hptr->h_name );
for ( pptr = hptr->h_aliases; *pptr != NULL; pptr++ )
printf("talias:%sn", *pptr );
switch( hptr->h_addrtype ){
case AF_INET:
pptr = hptr->h_addr_list;
for ( ; *pptr != NULL; pptr++ )
printf("taddress:%sn", *pptr );
// printf("taddress:%sn", 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:
As gethostbyname man page indicates, it points to the network addresses for the host (in network byte order)
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)