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 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): def is_valid_hostname(hostname):
if len(hostname) > 255: if len(hostname) > 255:
return False return False
@ -296,7 +284,7 @@ class DNSResolver(object):
parts = line.split() parts = line.split()
if len(parts) >= 2: if len(parts) >= 2:
server = parts[1] server = parts[1]
if is_ip(server) == socket.AF_INET: if common.is_ip(server) == socket.AF_INET:
if type(server) != str: if type(server) != str:
server = server.decode('utf8') server = server.decode('utf8')
self._servers.append(server) self._servers.append(server)
@ -316,7 +304,7 @@ class DNSResolver(object):
parts = line.split() parts = line.split()
if len(parts) >= 2: if len(parts) >= 2:
ip = parts[0] ip = parts[0]
if is_ip(ip): if common.is_ip(ip):
for i in range(1, len(parts)): for i in range(1, len(parts)):
hostname = parts[i] hostname = parts[i]
if hostname: if hostname:
@ -423,7 +411,7 @@ class DNSResolver(object):
hostname = hostname.encode('utf8') hostname = hostname.encode('utf8')
if not hostname: if not hostname:
callback(None, Exception('empty hostname')) callback(None, Exception('empty hostname'))
elif is_ip(hostname): elif common.is_ip(hostname):
callback((hostname, hostname), None) callback((hostname, hostname), None)
elif hostname in self._hosts: elif hostname in self._hosts:
logging.debug('hit hosts: %s', hostname) logging.debug('hit hosts: %s', hostname)

View file

@ -101,6 +101,18 @@ def inet_pton(family, addr):
raise RuntimeError("What family?") 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(): def patch_socket():
if not hasattr(socket, 'inet_pton'): if not hasattr(socket, 'inet_pton'):
socket.inet_pton = inet_pton socket.inet_pton = inet_pton