如何在基于Debian的系统上以编程方式获取IP地址?

gc *_*c . 3 c debian ip-address

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

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

127.0.0.1 localhost
127.0.1.1 mymachine

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

sig*_*ice 5

这里有一些快速而脏的代码演示了SIOCGIFCONF:

#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
    int sock, i;
    struct ifreq ifreqs[20];
    struct ifconf ic;

    ic.ifc_len = sizeof ifreqs;
    ic.ifc_req = ifreqs;

    sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("socket");
        exit(1);
    }

    if (ioctl(sock, SIOCGIFCONF, &ic) < 0) {
        perror("SIOCGIFCONF");
        exit(1);
    }

    for (i = 0; i < ic.ifc_len/sizeof(struct ifreq); ++i)
        printf("%s: %s\n", ifreqs[i].ifr_name,
                inet_ntoa(((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr));

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我在Linux机器上得到以下输出.

lo: 127.0.0.1
br0: 192.168.0.42
dummy1: 10.0.0.2
Run Code Online (Sandbox Code Playgroud)