Add random choice in asyncdns.py

This commit is contained in:
warriorpaw 2015-02-06 15:38:41 +08:00
parent e71ce6c758
commit 0e3e9776fd

View file

@ -24,7 +24,7 @@ import socket
import struct import struct
import re import re
import logging import logging
import random
from shadowsocks import common, lru_cache, eventloop from shadowsocks import common, lru_cache, eventloop
@ -336,12 +336,11 @@ class DNSResolver(object):
response = parse_response(data) response = parse_response(data)
if response and response.hostname: if response and response.hostname:
hostname = response.hostname hostname = response.hostname
ip = None ip = []
for answer in response.answers: for answer in response.answers:
if answer[1] in (QTYPE_A, QTYPE_AAAA) and \ if answer[1] in (QTYPE_A, QTYPE_AAAA) and \
answer[2] == QCLASS_IN: answer[2] == QCLASS_IN:
ip = answer[0] ip.append(answer[0])
break
if not ip and self._hostname_status.get(hostname, STATUS_IPV6) \ if not ip and self._hostname_status.get(hostname, STATUS_IPV6) \
== STATUS_IPV4: == STATUS_IPV4:
self._hostname_status[hostname] = STATUS_IPV6 self._hostname_status[hostname] = STATUS_IPV6
@ -349,7 +348,7 @@ class DNSResolver(object):
else: else:
if ip: if ip:
self._cache[hostname] = ip self._cache[hostname] = ip
self._call_callback(hostname, ip) self._call_callback(hostname, random.choice(ip))
elif self._hostname_status.get(hostname, None) == STATUS_IPV6: elif self._hostname_status.get(hostname, None) == STATUS_IPV6:
for question in response.questions: for question in response.questions:
if question[1] == QTYPE_AAAA: if question[1] == QTYPE_AAAA:
@ -413,7 +412,7 @@ class DNSResolver(object):
callback((hostname, ip), None) callback((hostname, ip), None)
elif hostname in self._cache: elif hostname in self._cache:
logging.debug('hit cache: %s', hostname) logging.debug('hit cache: %s', hostname)
ip = self._cache[hostname] ip = random.choice(self._cache[hostname])
callback((hostname, ip), None) callback((hostname, ip), None)
else: else:
if not is_valid_hostname(hostname): if not is_valid_hostname(hostname):