inet_ntoa只能转化IP地址 不能转域名的问题

在64位系统中,不能正确转化www.baidu.com。这样的域名地址。但可以转化192.168.0.1这样的实际地址。貌似32位系统是可以把www.baidu.com转化成具体的IP地址的。但可能也是转化成错误的地址,这个就不纠结了。

参考百度文章:htonl() htons()inet_ntoa() inet_addr()

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;
}
 


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值