免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2738 | 回复: 8
打印 上一主题 下一主题

这段代码为什么取到的ip地址是错的? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-09-20 21:11 |只看该作者 |倒序浏览
struct hostent *phe = NULL;                        /* host entry */       
        struct servent *pse = NULL;                        /* port number */
        struct protoent *ppe = NULL;                        /* protocol number */
        struct sockaddr_in sin;
        int s, type;
        char name[20];

        memset(&sin, 0, sizeof(sin));
        sin.sin_family = AF_INET;        /* Address Family: Internet IP Protocol         */

        gethostname(name, 20);
       
/* map hostname to ip address */
        if( phe = gethostbyname(name) )
                memset(&sin.sin_addr, phe->h_addr, phe->h_length);               
        printf("ip address is %s\n", inet_ntoa(sin.sin_addr));

主机名name是队的,phe也不是NULL,为什么打印出来的ip地址就不对呢?
机器只有一个网卡

论坛徽章:
0
2 [报告]
发表于 2006-09-21 00:09 |只看该作者
你应该用ioctl的SIOCGIFCONF方法获得接口IP.
man 7 netdevice

论坛徽章:
0
3 [报告]
发表于 2006-09-21 10:23 |只看该作者
but these codes used by somebody else in other programs work well, why i can't use it

Sorry for can't type Chinese now

论坛徽章:
0
4 [报告]
发表于 2006-09-21 16:04 |只看该作者
gethostbyname一般是先看/etc/hosts然后再调用dns吧?

论坛徽章:
0
5 [报告]
发表于 2006-09-21 22:38 |只看该作者
原帖由 zxw01 于 2006-9-21 10:23 发表
but these codes used by somebody else in other programs work well, why i can't use it

Sorry for can't type Chinese now


没那么多的but! 我已经告诉你正确的方法了!

论坛徽章:
0
6 [报告]
发表于 2006-09-21 22:42 |只看该作者
原帖由 hefish 于 2006-9-21 16:04 发表
gethostbyname一般是先看/etc/hosts然后再调用dns吧?


是的,确切地说是由/etc/host.conf的配置决定。

LZ贴出的代码就是很多文档中提到的取得IP的“Stupid”方法。会受到/etc/hosts等不可控因素的影响。

论坛徽章:
0
7 [报告]
发表于 2006-09-22 09:00 |只看该作者
sorry, 看的一本Douglas E.Comer写的internetworking with TCP/IP, 1998年出版的,有点老了

论坛徽章:
0
8 [报告]
发表于 2006-09-22 09:01 |只看该作者
是否与 /etc/nsswitch.conf 的配置有关?
例如

  1. #hosts:     db files nisplus nis dns
  2. hosts:      files dns
复制代码

这里表示了先找 /etc/hosts,再找 /etc/resolv.conf

论坛徽章:
0
9 [报告]
发表于 2006-09-22 09:12 |只看该作者
原帖由 JohnBull 于 2006-9-21 22:38 发表


没那么多的but! 我已经告诉你正确的方法了!


您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP