C gethostbyname()或getnameinfo()如何在后台工作?

C gethostbyname()或getnameinfo()如何在后台工作?,c,linux,sockets,C,Linux,Sockets,如何gethostbyname()或getnameinfo()在后台工作? #include <stdlib.h> #include <stdio.h> #include <netdb.h> /* paddr: print the IP address in a standard decimal dotted format */ void paddr(unsigned char *a) { printf("%d.%d.%d.%d\n", a[

如何
gethostbyname()
getnameinfo()
在后台工作?

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

/* paddr: print the IP address in a standard decimal dotted format */
void
paddr(unsigned char *a)
{
        printf("%d.%d.%d.%d\n", a[0], a[1], a[2], a[3]);
}

main(int argc, char **argv) {
        struct hostent *hp;
        char *host = "google.com";
        int i;

        hp = gethostbyname(host);
        if (!hp) {
                fprintf(stderr, "could not obtain address of %s\n", host);
                return 0;
        }
        for (i=0; hp->h_addr_list[i] != 0; i++)
                paddr((unsigned char*) hp->h_addr_list[i]);
        exit(0);
}
www.google.com的输出:

74.125.236.198
74.125.236.199
74.125.236.206
74.125.236.201
74.125.236.200
74.125.236.196
74.125.236.193
74.125.236.197
74.125.236.194
74.125.236.195
74.125.236.192
74.125.236.210
74.125.236.209
74.125.236.212
74.125.236.208
74.125.236.211
  • 上面的程序是否会在internet上执行检查以解析为IP
  • 为什么它在www.google.com上显示的IP地址更少,而在google.com上显示的IP地址更多

  • 在Linux系统上,glibc中实现的gethostbyname()调用根据配置文件/etc/host.conf/etc/nsswitch.conf执行查找

    通常在默认配置中,如果给定名称的本地条目存在,它将首先在/etc/hosts文件中查找,如果存在,则返回该条目。否则,它将继续使用DNS协议,该协议依次由/etc/resolv.conf配置,其中指定了名称服务器

    可以配置更复杂的设置来查找LDAP服务器、数据库等


    您还可以查看一些手册页,如
    man5nsswitch.conf

    您得到了什么输出?您希望得到什么样的输出?@DragonX(解释gethostbyname()的功能)。可能只有谷歌知道他们为google.com和www.google.com配置不同地址的技术原因。当你调用像
    gethostbyname
    这样的函数时,库只向一个或多个名称服务器(你的isp)发送请求,这些服务器可能会将请求转发到另一个名称服务器(例如谷歌的),或者可能返回缓存的回复,或者其他内容。您看到的内容取决于服务器返回到库中的名称。谷歌的名称服务器几乎肯定会进行负载平衡(也就是说,你不会每次都以相同的顺序获得相同的地址),而且它可能会做其他你不太清楚的事情。别费心了。你的咆哮部分地回答了你的问题,而且很有趣XD@DragonX正如rant所说,在任何配置合理的机器上,它基本上都会尝试/etc/hosts,然后使用DNS;关键是,NSS实际上总是使用DNS,但严格地说,它不必使用DNS,这是一个复杂的混乱局面(见gerrit的答案)