linux平台下怎么获取所有的本机IP?

algorithms_memo 2010-07-22 05:57:17
linux平台下怎么获取所有的本机IP?
...全文
204 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
algorithms_memo 2010-07-22
  • 打赏
  • 举报
回复
恩。我的意思是依赖于host文件配置。我希望不管hosts文件配置是否有问题,只要网卡正常工作(比如eth0)就能获取其IP。我在工作过程中碰到hosts有问题而eth0正常工作的情况。我是为了解决这样情形下的程序BUG
mymtom 2010-07-22
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 algorithms_memo 的回复:]

mymtom的方法依赖于hostname。当在/etc/hosts文件下没有对应项时,无法获取对应IP地址。
比如局域网192.168.100.100。设置/etc/hosts文件内容如下:
C/C++ code

127.0.0.1 localhost.localdomain localhost
::1 localhost6.local……
[/Quote]
gethostbyname不是简单地依赖/etc/hosts.
至少以下三个文件都会影响gethostbyname的结果
/etc/host.conf
/etc/hosts
/etc/nsswitch.conf
algorithms_memo 2010-07-22
  • 打赏
  • 举报
回复
mymtom的方法依赖于hostname。当在/etc/hosts文件下没有对应项时,无法获取对应IP地址。
比如局域网192.168.100.100。设置/etc/hosts文件内容如下:

127.0.0.1 localhost.localdomain localhost
::1 localhost6.localdomain6 localhost6

则无法获取192.168.100.100地址。
mymtom 2010-07-22
  • 打赏
  • 举报
回复

/*-
* Copyright (C), 1988-2010, XXX Co., Ltd.
*
* $Id$
*
* $Log$
*/
#ifndef lint
static const char rcsid[] =
"$Id$";
static const char relid[] =
"$" "Date: "__FILE__" "__DATE__" "__TIME__" $";
#endif /* not lint */

/**
* @file
* @brief
*/


#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

#include <stdio.h>
#include <stdlib.h>

int print_host(const char *name, struct hostent *host)
{
char **alias;
int count;
struct in_addr addr;

(void)printf("%s: %s\n", "Official name", host->h_name);
count = 0;
for (alias = host->h_aliases; *alias; alias++)
(void)printf("%s #%d: %s\n", "Aliases", ++count, *alias);

switch (host->h_addrtype) {
case AF_INET:
break;
default:
break;
}

count = 0;
if (AF_INET == host->h_addrtype) {
while (host->h_addr_list[count]) {
addr.s_addr = *(in_addr_t *)host->h_addr_list[count++];
(void)printf("%s #%d: %s\n", "IP Address", count, inet_ntoa(addr));
}
}

printf("\n");

return 0;
}

int main(int argc, char *argv[])
{
int count;
char name[HOST_NAME_MAX + 1];
struct hostent *host;
struct in_addr addr;

if (argc >= 2) {
for (count = 1; count < argc; count++)
if (inet_aton(argv[count], &addr)) {
if (!!(host = gethostbyaddr(&addr, sizeof(addr), AF_INET)))
(void)print_host(argv[count], host);
else
(void)printf("%s %s %s\n\n", "address", argv[count], "NOT FOUND");
} else {
if (!!(host = gethostbyname(argv[count])))
(void)print_host(argv[count], host);
else
(void)printf("%s %s %s\n\n", "name", argv[count], "NOT FOUND");
}
} else {
gethostname(name, sizeof(name));
if (NULL != (host = gethostbyname(name)))
(void)print_host(name, host);
else
(void)printf("%s %s %s\n\n", "name", argv[count], "NOT FOUND");
}

return 0;
}
gundamy 2010-07-22
  • 打赏
  • 举报
回复
使用libpcap库
mymtom 2010-07-22
  • 打赏
  • 举报
回复
gethostbyname?

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧