本文整理汇总了Python中socket.gaierror函数的典型用法代码示例。如果您正苦于以下问题:Python gaierror函数的具体用法?Python gaierror怎么用?Python gaierror使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gaierror函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getnameinfo
def getnameinfo(address, flags):
dns.build_resolver()
try:
host, port = address
except (ValueError, TypeError):
if not isinstance(address, tuple):
del address
raise TypeError('getnameinfo() argument must be a tuple')
else:
raise socket.gaierror(
socket.EAI_NONAME, "Name or service not known")
if (flags & socket.NI_NAMEREQD) and (flags & socket.NI_NUMERICHOST):
raise socket.gaierror(
socket.EAI_NONAME, "Name or service not known")
if dns.is_ipv4(host):
try:
name = dns.reversename.from_address(host)
results = dns.resolver_obj.query(name, dns.rdatatype.PTR)
if len(results) > 1:
raise socket.error(
"sockaddr resolved to multiple addresses")
host = results[0].target.to_text(omit_final_dot=True)
except dns.exception.Timeout, exc:
if flags & socket.NI_NAMEREQD:
raise socket.gaierror(socket.EAI_AGAIN, 'Lookup timed out')
except dns.resolver.NXDOMAIN:
return (host, str(port))
示例2: fake_gethostbyname
def fake_gethostbyname(hostname):
try:
host_ip = None
# for templates/index.py
if hostname == config.get("broker", "bind_address"):
host_ip = gethostbyname_orig(hostname)
else:
# faking hostip
fake_hosts = config.get("unittest", "fake_hosts_location")
hostfilename = fake_hosts + hostname
# strip domain part
if not os.path.exists(hostfilename) and hostname.find(".") > -1:
hostfilename = fake_hosts + hostname[: hostname.find(".")]
hostfile = open(hostfilename).readlines()
primary_name = hostfile[0].split()[2]
ip_re = re.compile(r"^\s*([a-z0-9]+)\s+[a-z0-9]+\s+([0-9\.]+)")
for line in hostfile:
m = ip_re.search(line)
if m and primary_name == m.group(1):
host_ip = m.group(2)
break
if host_ip == None:
raise gaierror(-2, "Name or service not known")
return host_ip
except IOError, e:
# To have the cause in aqd.log
raise gaierror(-2, "Name or service not known %s" % e)
示例3: do_resolve
def do_resolve(query, dnsserver, timeout, queobj):
if isinstance(query, basestring):
qtype = dnslib.QTYPE.AAAA if ':' in dnsserver else dnslib.QTYPE.A
query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query, qtype=qtype))
query_data = query.pack()
sock_family = socket.AF_INET6 if ':' in dnsserver else socket.AF_INET
sock = socket.socket(sock_family)
rfile = None
try:
sock.settimeout(timeout or None)
sock.connect(parse_hostport(dnsserver, 53))
sock.send(struct.pack('>h', len(query_data)) + query_data)
rfile = sock.makefile('r', 1024)
reply_data_length = rfile.read(2)
if len(reply_data_length) < 2:
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsserver))
reply_data = rfile.read(struct.unpack('>h', reply_data_length)[0])
record = dnslib.DNSRecord.parse(reply_data)
iplist = [str(x.rdata) for x in record.rr if x.rtype in (1, 28, 255)]
if any(x in blacklist for x in iplist):
logging.debug('query=%r dnsserver=%r record bad iplist=%r', query, dnsserver, iplist)
raise socket.gaierror(11004, 'getaddrinfo %r from %r failed' % (query, dnsserver))
else:
logging.debug('query=%r dnsserver=%r record iplist=%s', query, dnsserver, iplist)
queobj.put(record)
except socket.error as e:
logging.debug('query=%r dnsserver=%r failed %r', query, dnsserver, e)
queobj.put(e)
finally:
if rfile:
rfile.close()
sock.close()
示例4: getnameinfo
def getnameinfo(sockaddr, flags):
"""Replacement for Python's socket.getnameinfo.
Currently only supports IPv4.
"""
host, port = sockaddr
if (flags & socket.NI_NAMEREQD) and (flags & socket.NI_NUMERICHOST):
# Conflicting flags. Punt.
raise socket.gaierror(
(socket.EAI_NONAME, 'Name or service not known'))
if is_ipv4_addr(host):
try:
rrset = resolver.query(
dns.reversename.from_address(host), dns.rdatatype.PTR)
if len(rrset) > 1:
raise socket.error('sockaddr resolved to multiple addresses')
host = rrset[0].target.to_text(omit_final_dot=True)
except dns.exception.Timeout, e:
if flags & socket.NI_NAMEREQD:
raise socket.gaierror((socket.EAI_AGAIN, 'Lookup timed out'))
except dns.exception.DNSException, e:
if flags & socket.NI_NAMEREQD:
raise socket.gaierror(
(socket.EAI_NONAME, 'Name or service not known'))
示例5: test_no_internet
def test_no_internet(monkeypatch):
# No crash occur if the computer don't have access to internet.
from socket import gaierror
monkeypatch.setattr(boc_currency_provider, 'urlopen', exception_raiser(gaierror()))
monkeypatch.setattr(yahoo_currency_provider, 'urlopen', exception_raiser(gaierror()))
with raises(RateProviderUnavailable):
boc_currency_provider.BOCProviderPlugin().wrapped_get_currency_rates(
'USD', date(2008, 5, 20), date(2008, 5, 20)
)
yahoo_currency_provider.YahooProviderPlugin().wrapped_get_currency_rates(
'LVL', date(2008, 5, 20), date(2008, 5, 20)
)
示例6: dnslib_resolve_over_tcp
def dnslib_resolve_over_tcp(query, dnsservers, timeout, **kwargs):
"""dns query over tcp"""
if not isinstance(query, (basestring, dnslib.DNSRecord)):
raise TypeError("query argument requires string/DNSRecord")
blacklist = kwargs.get("blacklist", ())
def do_resolve(query, dnsserver, timeout, queobj):
if isinstance(query, basestring):
qtype = dnslib.QTYPE.AAAA if ":" in dnsserver else dnslib.QTYPE.A
query = dnslib.DNSRecord(q=dnslib.DNSQuestion(query, qtype=qtype))
query_data = query.pack()
sock_family = socket.AF_INET6 if ":" in dnsserver else socket.AF_INET
sock = socket.socket(sock_family)
rfile = None
try:
sock.settimeout(timeout or None)
sock.connect(parse_hostport(dnsserver, 53))
sock.send(struct.pack(">h", len(query_data)) + query_data)
rfile = sock.makefile("r", 1024)
reply_data_length = rfile.read(2)
if len(reply_data_length) < 2:
raise socket.gaierror(11004, "getaddrinfo %r from %r failed" % (query, dnsserver))
reply_data = rfile.read(struct.unpack(">h", reply_data_length)[0])
record = dnslib.DNSRecord.parse(reply_data)
iplist = [str(x.rdata) for x in record.rr if x.rtype in (1, 28, 255)]
if any(x in blacklist for x in iplist):
logging.debug("query=%r dnsserver=%r record bad iplist=%r", query, dnsserver, iplist)
raise socket.gaierror(11004, "getaddrinfo %r from %r failed" % (query, dnsserver))
else:
logging.debug("query=%r dnsserver=%r record iplist=%s", query, dnsserver, iplist)
queobj.put(record)
except socket.error as e:
logging.debug("query=%r dnsserver=%r failed %r", query, dnsserver, e)
queobj.put(e)
finally:
if rfile:
rfile.close()
sock.close()
queobj = Queue.Queue()
for dnsserver in dnsservers:
thread.start_new_thread(do_resolve, (query, dnsserver, timeout, queobj))
for i in range(len(dnsservers)):
try:
result = queobj.get(timeout)
except Queue.Empty:
raise socket.gaierror(11004, "getaddrinfo %r from %r failed" % (query, dnsservers))
if result and not isinstance(result, Exception):
return result
elif i == len(dnsservers) - 1:
logging.warning("dnslib_resolve_over_tcp %r with %s return %r", query, dnsservers, result)
raise socket.gaierror(11004, "getaddrinfo %r from %r failed" % (query, dnsservers))
示例7: test_gaierror
def test_gaierror(self):
"""
L{error.getConnectError} converts to a L{error.UnknownHostError} given
a C{socket.gaierror} instance.
"""
result = error.getConnectError(socket.gaierror(12, "hello"))
self.assertCorrectException(12, "hello", result, error.UnknownHostError)
示例8: test_should_reject_false
def test_should_reject_false(self, lookup_call):
import socket
lookup_call.side_effect = socket.gaierror("foobar")
dnsbl = self._make_one()
self.assertFalse(dnsbl.should_reject({"ip_address": "10.0.100.1"}))
lookup_call.assert_called_with("1.100.0.10.xbl.spamhaus.org.")
示例9: getaddrinfo
def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
"""
Mock for L{socket.getaddrinfo}.
@param host: see L{socket.getaddrinfo}
@param port: see L{socket.getaddrinfo}
@param family: see L{socket.getaddrinfo}
@param socktype: see L{socket.getaddrinfo}
@param proto: see L{socket.getaddrinfo}
@param flags: see L{socket.getaddrinfo}
@return: L{socket.getaddrinfo}
"""
self.calls.append((host, port, family, socktype, proto, flags))
results = self.results[host]
if results:
return results
else:
raise gaierror(EAI_NONAME,
'nodename nor servname provided, or not known')
示例10: httpLocThatRequiresAProxy
def httpLocThatRequiresAProxy(loc):
import networking
if networking.config._useProxy:
return fauxrootOpen(loc)
sleep()
sockErr = socket.gaierror(110, 'Connection timed out')
raise urllib2.URLError(sockErr)
示例11: mocked_socket_gethostbyname
def mocked_socket_gethostbyname(domain):
claimed_domains = ["google.com"]
if domain not in claimed_domains:
from socket import gaierror
raise gaierror("[Errno -2] Name or service not known")
else:
return '216.58.221.46'
示例12: test_connection_error
def test_connection_error(self):
reason = socket.gaierror(8, 'nodename nor servname provided')
self.urlopen_mock.side_effect = urllib2.URLError(reason)
tasks.fetch_manifest('url', self.upload.pk)
self.check_validation(
'No manifest was found at that URL. Check the address and try '
'again.')
示例13: _fast_getaddrinfo
def _fast_getaddrinfo(host, *args, **kwargs):
def needs_dns_resolving(host2):
try:
ipaddress.ip_address(host2)
return False # already valid IP
except ValueError:
pass # not an IP
if str(host) in ('localhost', 'localhost.',):
return False
return True
try:
if needs_dns_resolving(host):
answers = dns.resolver.query(host)
addr = str(answers[0])
else:
addr = host
except dns.exception.DNSException as e:
# dns failed for some reason, e.g. dns.resolver.NXDOMAIN
# this is normal. Simply report back failure:
raise socket.gaierror(11001, 'getaddrinfo failed') from e
except BaseException as e:
# Possibly internal error in dnspython :( see #4483
# Fall back to original socket.getaddrinfo to resolve dns.
print_error('dnspython failed to resolve dns with error:', e)
addr = host
return socket._getaddrinfo(addr, *args, **kwargs)
示例14: test_retry_dns_error
def test_retry_dns_error(self):
with mock.patch('socket.gethostbyname',
side_effect=socket.gaierror(-5, 'No address associated with hostname')):
crawler = get_crawler(SimpleSpider)
with LogCapture() as l:
yield crawler.crawl("http://example.com/")
self._assert_retried(l)
示例15: test_run_command_exception_gaierror
def test_run_command_exception_gaierror(self):
"""Testing socket.gaierror in run_command."""
self.connection._telnet = mock.Mock()
self.connection._telnet.write = mock.Mock()
self.connection._telnet.write.side_effect = socket.gaierror('except')
self.connection.run_command('test')
self.assertFalse(self.connection._connected)