在64位系统中,不能正确转化www.baidu.com。这样的域名地址。但可以转化192.168.0.1这样的实际地址。貌似32位系统是可以把www.baidu.com转化成具体的IP地址的。但可能也是转化成错误的地址,这个就不纠结了。
参考百度文章:h
http://wenku.baidu.com/view/4bf57790daef5ef7ba0d3c0c.html
在这种情况下,可以使用inet_ntop取代。glibc手册也建议用这个取代inet_ntoa(Instead of inet_ntoa the newer function inet_ntop which is described below should
be used since it handles both IPv4 and IPv6 addresses.)
代码如下:
#include <netdb.h>
#include <sys/socket.h>
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
char *ptr, **pptr;
struct hostent *hptr;
char str[32];
if(argv[1]!=NULL){
ptr = argv[1];
} else{
ptr = "www.baidu.com";
}
if((hptr = gethostbyname(ptr)) == NULL)
{
printf(" gethostbyname error for host:%s\n", ptr);
return 0;
}
printf("official hostname:%s\n",hptr->h_name);
for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
printf(" alias:%s\n",*pptr);
switch(hptr->h_addrtype)
{
case AF_INET:
case AF_INET6:
printf("first address: %s\n", inet_ntop(AF_INET, hptr->h_addr, str, 32));
char * IP=(char *)inet_ntop(AF_INET, hptr->h_addr, str, 32);
printf("addr = %s\n",IP);
break;
default:
printf("unknown address type\n");
break;
}
return 0;
}