首页  >  问答  >  正文

linux - hosts文件一个主机名对应多个ip,为什么不成功??

uname -a

Linux XXXX 3.10.0-123.9.3.el7.x86_64 #1 SMP Thu Nov 6 15:06:03 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux

修改了/etc/host.con文件
order hosts,bind
multi on

也修改了/etc/hosts文件
192.168.0.1 a
192.168.0.2 a
192.168.0.3 a

3个ip都是a主机的ip

为什么ping a的时候就只能是第一条(192.168.0.1 a)生效了???

高洛峰高洛峰2744 天前1241

全部回复(1)我来回复

  • ringa_lee

    ringa_lee2017-04-17 17:02:01

    研究了一下:查看host.conf的手册可以看到说明:

    multi : Valid values are on and off. If set to on, the resolver library will return all valid addresses for a host that appears in the /etc/hosts file, instead of only the first. This is off by default, as it may cause a substantial performance loss at sites with large hosts files.

    the resolver library 并不是ping, ping只会取get的第一条,可以个通过:

    getent hosts a
    

    来获取hosts配置中的有效配置,getent命令用于获取一下重要配置文件的内容,
    getnet hosts其实最终是通过调用gethostbyname系统api函数来进行解析的,所以可以通过在代码中调用gethostbyname来获取 server name所对应的所以ip,下面是随便找的一段代码:

    #include <iostream>
    #include <typeinfo>
    
    #include <netdb.h>
    #include <sys/socket.h>
    #include <arpa/inet.h>
    #include <stdio.h>
    
    int main(int argc, char **argv)
    {
        char   *ptr, **pptr;
        struct hostent *hptr;
        char   str[32];
        ptr = argv[1];
    
        if((hptr = gethostbyname(ptr)) == NULL)
        {
            printf(" gethostbyname error for host:%s\n", ptr);
            return 0;
        }
    
        printf("official hostname:%s\n",hptr->h_name);
        for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
            printf(" alias:%s\n",*pptr);
    
        switch(hptr->h_addrtype)
        {
            case AF_INET:
            case AF_INET6:
                pptr=hptr->h_addr_list;
                for(; *pptr!=NULL; pptr++)
                    printf(" address:%s\n",
                           inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
                printf(" first address: %s\n",
                           inet_ntop(hptr->h_addrtype, hptr->h_addr, str, sizeof(str)));
            break;
            default:
                printf("unknown address type\n");
            break;
        }
    
        return 0;
    }

    执行结果:

    $./a.out a
    official hostname:a
     address:187.0.0.3
     address:127.0.0.1
     address:127.0.0.2
     first address: 187.0.0.3

    回复
    0
  • 取消回复