Move is_ip from asyncdns to common

Since implement CIDR forbidden need this function,
move it to common file seems to be a better choice.
This commit is contained in:
Sunny 2015-01-31 11:56:17 +08:00
parent ada97ab6d9
commit 8783e0e9ae
2 changed files with 15 additions and 15 deletions

View file

@ -233,18 +233,6 @@ def parse_response(data):
return None
def is_ip(address):
for family in (socket.AF_INET, socket.AF_INET6):
try:
if type(address) != str:
address = address.decode('utf8')
socket.inet_pton(family, address)
return family
except (TypeError, ValueError, OSError, IOError):
pass
return False
def is_valid_hostname(hostname):
if len(hostname) > 255:
return False
@ -296,7 +284,7 @@ class DNSResolver(object):
parts = line.split()
if len(parts) >= 2:
server = parts[1]
if is_ip(server) == socket.AF_INET:
if common.is_ip(server) == socket.AF_INET:
if type(server) != str:
server = server.decode('utf8')
self._servers.append(server)
@ -316,7 +304,7 @@ class DNSResolver(object):
parts = line.split()
if len(parts) >= 2:
ip = parts[0]
if is_ip(ip):
if common.is_ip(ip):
for i in range(1, len(parts)):
hostname = parts[i]
if hostname:
@ -423,7 +411,7 @@ class DNSResolver(object):
hostname = hostname.encode('utf8')
if not hostname:
callback(None, Exception('empty hostname'))
elif is_ip(hostname):
elif common.is_ip(hostname):
callback((hostname, hostname), None)
elif hostname in self._hosts:
logging.debug('hit hosts: %s', hostname)

View file

@ -101,6 +101,18 @@ def inet_pton(family, addr):
raise RuntimeError("What family?")
def is_ip(address):
for family in (socket.AF_INET, socket.AF_INET6):
try:
if type(address) != str:
address = address.decode('utf8')
inet_pton(family, address)
return family
except (TypeError, ValueError, OSError, IOError):
pass
return False
def patch_socket():
if not hasattr(socket, 'inet_pton'):
socket.inet_pton = inet_pton