c - 为什么我只看到带有此代码的主机的 inet 地址之一?

标签 c networking network-programming

我刚刚写了这个片段:

#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>

int main(void)
{
    sockaddr_in self;
    hostent *he;
    char local[HOST_NAME_MAX];
    gethostname(local, sizeof(local));
    he = gethostbyname(local);

    if (he)
    {
        std::cout << "Addresses: " << std::endl;
        unsigned int i = 0;
        while(he->h_addr_list[i] != NULL)
        {
            std::cout << "\t" << i << " --> ";
            memcpy(&self.sin_addr, he->h_addr_list[i], he->h_length);
            std::cout << self.sin_addr.s_addr;
            std::cout << " ( " << inet_ntoa( *( struct in_addr*)( he-> h_addr_list[i])) << " )" << std::endl;
            i++;
        }
    }
    else
        std::cout << "gethostname failed" << std::endl;
}

当我在示例主机上运行它时,我得到类似这样的东西(不过我在这里编写了这些地址):

地址: 0 --> 1307150150 ( 10.23.215.61 )

而如果我运行ifconfig,我会得到更多的输出,特别是当至少有两个以上时,上面的地址仅对应于ifconfig显示的第一个界面在 eth0 之前。怎么会?我本希望它能遍历该主机中所有可能的网络地址...

在回答以下问题后,我执行了以下操作(使用 getaddrinfo):

int main(void)
{
    struct addrinfo *result;
    struct addrinfo *res;
    int error;

    char local[HOST_NAME_MAX];
    gethostname(local, sizeof(local));

    error = getaddrinfo(local, NULL, NULL, &result);
    if (error != 0)
    {
        fprintf(stderr, "error in getaddrinfo: %s\n", gai_strerror(error));
        return 1;
    }

    for (res = result; res != NULL; res = res->ai_next)
    {
        struct in_addr addr;
        addr.s_addr = ((struct sockaddr_in *)(res->ai_addr))->sin_addr.s_addr;
        std::cout << addr.s_addr
                  << " ("
                  << inet_ntoa(addr)
                  << " )"
                  << std::endl;
    }

    freeaddrinfo(result);
}

我现在得到与以前相同的输出......除了重复“正确”的次数。 (即,从 ifconfig 中,我看到三个接口(interface),我可以从这些接口(interface)以多播方式发送消息,并且我得到第一个接口(interface)的 inet 地址,重复三次作为上面的输出。

最佳答案

函数gethostname返回主机已配置的名称。您可以使用您选择的任何名称来配置的计算机。

函数gethostbyname为您的操作系统执行“正常”名称解析过程。通常,它会首先查看您的 /etc/hosts 并失败查询您的 DNS 解析器。

要让 gethostbyname 返回所有配置的 IP 地址,您必须将它们放入 /etc/hosts 文件中,或者要求您的 DNS 管理员更新您的服务器.

顺便说一下,gethostbyname 已被弃用,取而代之的是 getaddrinfo .

关于c - 为什么我只看到带有此代码的主机的 inet 地址之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14017796/

相关文章:

.net - 共享数据库的 Windows 窗体的最佳设计?

networking - 如何开始 p2p 网络编程?

c - 运行机器代码时出现模糊的运行时错误

c - 如何读取 .txt 文件中的特定值,然后将其与另一个值进行比较?

c - 无法设置套接字选项 IPV6 多播 : No such device error

mysql - Docker Node 应用程序无法连接链接的mysql容器

linux - IP 邻居获取 IPV4 地址

c - 如何计算迭代和递归解?

C - 为什么在将单个字符分配给数组时自动添加字符串终止符?

networking - 自动检测连接到网络的新计算机