免费注册 查看新帖 |

Chinaunix

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

一个关于gethostbyname()问题,很疑惑? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-01-28 15:00 |只看该作者 |倒序浏览
我记得gethostbyname()可以取到以太网接口地址,怎么现在就能取道环回接口地址?下面的代码只能取到环回接口,为什么呢?


  1. #include <netinet/in.h>
  2. #include <sys/types.h>
  3. #include <arpa/inet.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <netdb.h>
  7. #include <stdio.h>

  8. void err_sys(const char *errmsg);

  9. int main(int argc, char **argv)
  10. {
  11.         struct hostent *h;
  12.         char hostname[] = "localhost.localdomain";
  13.         char addr[INET_ADDRSTRLEN];
  14.         int i;       

  15.         if ((h = gethostbyname(hostname)) == NULL) {
  16.                 fprintf(stderr, "gethostbyname error: %s\n", hstrerror(h_errno));
  17.                 exit(1);
  18.         }
  19.        
  20.         for (i = 0; h->h_addr_list[i] != NULL; i++) {
  21.                 if (inet_ntop(AF_INET, h->h_addr_list[i], addr, sizeof(addr)) == NULL)
  22.                         err_sys("inet_ntop error");
  23.                 else
  24.                         printf("IP address: %s\n", addr);
  25.         }

  26.         exit(0);
  27. }

  28. void err_sys(const char *errmsg)
  29. {
  30.         perror(errmsg);
  31.        
  32.         exit(1);
  33. }
复制代码


怎么搞的呢?

论坛徽章:
0
2 [报告]
发表于 2007-01-28 15:03 |只看该作者
运行结果

[root@localhost root]# gcc 1.c -o 1
[root@localhost root]# ./1
IP address: 127.0.0.1
[root@localhost root]#

论坛徽章:
0
3 [报告]
发表于 2007-01-28 15:53 |只看该作者
难道不对吗、、、???

论坛徽章:
0
4 [报告]
发表于 2007-01-28 17:44 |只看该作者
原帖由 只爱殷澍蕾 于 2007-1-28 15:00 发表
我记得gethostbyname()可以取到以太网接口地址


This is a really bad and stupid idea.
Please use ioctl(...SIOCGIFCONF...) instead.

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

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP