免费注册 查看新帖 |

Chinaunix

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

这段代码为什么取不到本机的所有ip呢?~~~~~~~~~~ [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-01-04 10:05 |只看该作者 |倒序浏览
我是一新手希望各位前辈多多帮忙。
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>       
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>       

int main(int argc, char **argv)
{
        char acHostName[128] = {0};
        struct        hostent *pHe = NULL;
        int i;
        char **ppc = NULL;
        char acAddrName[128] = {0};
       
        gethostname(acHostName, sizeof(acHostName));
        pHe = gethostbyname(acHostName);
        printf("正式名字:%s\n", pHe->h_name);
        ppc = pHe->h_addr_list;
        for (i = 0; ppc != NULL; i++)

        {
             acAddrName[0] = 0;
             inet_ntop(pHe->h_addrtype, ppc, acAddrName, sizeof(acAddrName ));
                printf("%s\n", acAddrName );

        }
       
        return 0;
}       

只取到了127.0.0.1 他的ip是192.168.0.253可这段代码在windows上却可以取到,这是为什么?
是不是linux上不是这么做,而是用其他的方法取得本机ip的?

[ 本帖最后由 xiaoligang 于 2007-1-4 13:33 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2007-01-04 10:57 |只看该作者
gethostname()和gethostbyname()读取的是/etc/hosts这个文件中,机器名和IP地址的对应关系

论坛徽章:
0
3 [报告]
发表于 2007-01-04 11:07 |只看该作者
那我怎样才能取得本机的所有ip呢(或者说所有接口)?

论坛徽章:
0
4 [报告]
发表于 2007-01-04 11:52 |只看该作者
getifaddrs()

论坛徽章:
0
5 [报告]
发表于 2007-01-04 12:20 |只看该作者
fd = socked(AF_INET,SOCK_DGRAM,0);
ioctl(fd,SIOCGIFCONF,&ifconf);

google一下吧.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP