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

查看:243
本文介绍了在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 mymachine

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 ls man 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天全站免登陆