linux - 一个域名对应多个 IP
伊谢尔伦
伊谢尔伦 2017-04-17 11:32:35
[Linux讨论组]

我想问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.这种顺序有何作用?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(1)
大家讲道理

这个叫 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】的客户端。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号