Home  >  Q&A  >  body text

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 days ago1247

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 17:02:01

    Researched it: Check the manual of host.conf and you can see the instructions:

    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 is not ping, ping will only take the first one of get, you can pass:

    getent hosts a
    

    To get the effective configuration in the hosts configuration, the getent command is used to get the contents of important configuration files.
    getnet hosts is actually ultimately parsed by calling the gethostbyname system api function, so you can get the server by calling gethostbyname in the code The IP corresponding to the name is as follows:

    #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;
    }

    Execution result:

    $./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

    reply
    0
  • Cancelreply