一个域名对应多个 IP

永恒少侠
  • 375

我想问2个问题,在提问前,我先进行下说明。
在Linux下编译(gcc -o hostinfo hostinfo.c)下面的代码后

#include<stdio.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<netinet/in.h>

int main(int argc, char **argv)
{
    if(argc != 2){
         fprintf(stderr, "usage: %s <domain name or dotted-decimal>\n", argv[0]);
         return 0;
    }

   char **pp;
   struct in_addr addr;
   struct hostent *hostp;

   if(inet_aton(argv[1], &addr) != 0){
       hostp = gethostbyaddr((const char *)&addr, sizeof(addr), AF_INET);
   }else{
       hostp = gethostbyname(argv[1]);
   }

   printf("official hostname: %s\n", hostp->h_name);

   for(pp = hostp->h_aliases; *pp != NULL; pp++){
        printf("alias: %s\n", *pp);
   }

   for(pp = hostp->h_addr_list; *pp != NULL; pp++){
        addr.s_addr = ((struct in_addr *) *pp)->s_addr;
        printf("address: %s\n", inet_ntoa(addr));
   }

   return 0;
}

运行命令:

>./hostinfo www.17173.com
>./hostinfo www.17173.com

得到结果如下:

official hostname: poolct.17173.com
alias: www.17173.com
alias: pooldist.17173.com
address: 117.27.230.84
address: 117.27.230.82
address: 117.27.230.83
address: 117.27.230.98
address: 117.27.230.75
address: 117.27.230.86
address: 117.27.230.85
address: 117.27.230.80
address: 117.27.230.99  

official hostname: poolct.17173.com
alias: www.17173.com
alias: pooldist.17173.com
address: 117.27.230.83
address: 117.27.230.82
address: 117.27.230.84
address: 117.27.230.96
address: 117.27.230.75
address: 117.27.230.88
address: 117.27.230.85
address: 117.27.230.80
address: 117.27.230.99

现在我想请问2个问题:
A.为什么每次返回的 ip 地址的顺序不一样?
B.这种顺序有何作用?

回复
阅读 9.9k
1 个回答
qinjianxiang
  • 5.9k
✓ 已被采纳

这个叫 DNS轮询(Round-robin DNS),是一种简单的负载均衡技术,维基百科上有详细介绍:

http://en.wikipedia.org/wiki/Round-robin_DNS

文中说道:

With each DNS response, the IP address sequence in the list is
permuted. Usually, basic IP clients attempt connections with the first
address returned from a DNS query so that on different connection
attempts clients would receive service from different providers, thus
distributing the overall load among servers.

你的两个问题,答案都在其中:

  • DNS服务器在收到每个请求时,都会重新(随机)排序多个IP,然后返回给客户端。这就是你观察到的每次返回的IP顺序不一样。

  • 这样做的原因是负载均衡,因为客户端很可能默认选取DNS服务器返回的第一个IP来建立连接,如果每次返回的IP顺序都一样,所有流量都跑到第一个IP上去了,失去了负载均衡的意义。当然也有聪明的客户端会从DNS返回的IP列表中随机选取一个建立连接,但这与服务端的随机顺序并不冲突,服务端这样做兼容了【默认选取第一个IP】的客户端。

宣传栏