如何在基于 Debian 的系统上以编程方式获取 IP 地址? [英] How to get IP address programmatically on Debian based system?

查看:22
本文介绍了如何在基于 Debian 的系统上以编程方式获取 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的程序中检索本地计算机的 IP 地址.操作系统是 Ubuntu 8.10.我尝试使用 gethostname()gethostbyname() 来检索 IP 地址.我收到的答案是127.0.1.1.我了解到这似乎是 Debian 的事情:这里链接的文档解释了这个想法.

I'm trying to retrieve the IP Address of the local machine in my program. The Operating System is Ubuntu 8.10. I tried using gethostname() and gethostbyname() to retrieve the IP Address. The answer I received is 127.0.1.1. I learned that it seems to be a Debian thing: The document linked here explained the idea.

我的 /etc/hosts 文件的内容是:

The content of my /etc/hosts file is:

127.0.0.1 本地主机
127.0.1.1 我的机器

127.0.0.1 localhost
127.0.1.1 mymachine

在这种情况下,有没有其他方法可以在不修改机器上的系统文件的情况下以编程方式(首选 C 或 C++)获取 IP 地址?

In this case, is there any other way to programmatically (prefer C or C++) to get the IP Address without modifying the system file on the machine?

推荐答案

查看netdevice",通过man netdevice在网络上.
然后可以使用 SIOCGIFCONF 来获取所有传输层地址的枚举.

See "netdevice", through man netdevice or on the web.
SIOCGIFCONF can then be used to get an enumeration of all transport layer addresses.

编辑(在手册页上):man 在 Linux(或其他类似 UNIX 的系统)上是一个非常有用的命令.它显示了大多数命令、库函数、程序等的简要说明.打开 shell 提示符并键入 man lsman netdevice,你就会明白我的意思了.

Edit (on manpages): man is a very useful command on Linux (or other UNIX-like systems as well). It shows a brief description of most commands, library functions, programs, etc. Open a shell prompt and type man ls or man netdevice, and you'll see what I mean.

编辑(关于 IP 的一般检索):最简单的方法,如果您认为 C 方法太乱,是一个简单的 shell 脚本,例如(只是从我的脑海中):
ifconfig|grep 'inet addr'|awk '{print $2}'|sed 's/addr://g'

Edit (on general retrieving of IP): The easiest way, if you think the C way is too messy, is a simple shell script like (just from the top of my head):
ifconfig|grep 'inet addr'|awk '{print $2}'|sed 's/addr://g'

编辑(关于大脑解决方案):他所做的是使用 if_nameindex() 函数用于查找所有网络设备名称,然后对每个名称执行 SIOCFIFCONF ioctl 以查找其 IP.正如他所说,它只列出每台设备一个 IP.

Edit (on the Brain solution): What he does is using the if_nameindex() function for finding all network device names, and then the SIOCFIFCONF ioctl on each of these names for finding their IP. As he says, it only lists one IP per device.

这篇关于如何在基于 Debian 的系统上以编程方式获取 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆