Python _socket.gaierror() Examples

The following are 30 code examples of _socket.gaierror(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module _socket , or try the search function .
Example #1
Source File: helpers.py    From panoptes with Apache License 2.0 6 votes vote down vote up
def get_hostnames(ips, timeout):
    """
    Do DNS resolution for a given list of IPs

    Args:
        ips (list): A list of IPs
        timeout (int): The number of seconds to wait for resolution of **all** IPs

    Returns:
        list: A list of (address, hosname) tuples in the same order as the input list of IPs
    """
    assert validators.PanoptesValidators.valid_nonempty_iterable_of_strings(ips), u'ips should be a list'
    assert validators.PanoptesValidators.valid_nonzero_integer(timeout), u'timeout should be an int greater than zero'

    jobs = [gevent.spawn(wrap_errors((gaierror, herror), socket.gethostbyaddr), ip) for ip in ips]
    gevent.joinall(jobs, timeout=timeout)
    hostnames = [None if isinstance(job.get(), (gaierror, herror)) else job.value for job in jobs]
    results = {
        ips[i]: unknown_hostname(ips[i]) if ((not result) or
                                             (not result[0]) or
                                             result[0].startswith(u'UNKNOWN'))
        else result[0]
        for i, result in enumerate(hostnames)}
    return results 
Example #2
Source File: test__socket.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_getnameinfo(self):
        '''Tests _socket.getnameinfo()'''
        #sanity
        _socket.getnameinfo(("127.0.0.1", 80), 8)
        _socket.getnameinfo(("127.0.0.1", 80), 9)
            
        host, service = _socket.getnameinfo( ("127.0.0.1", 80), 8)
        self.assertEqual(service, '80')
            
        host, service = _socket.getnameinfo( ("127.0.0.1", 80), 0)
        self.assertEqual(service, "http")
        #IP gives a TypeError
        #self.assertRaises(SystemError, _socket.getnameinfo, ("127.0.0.1"), 8)
        #self.assertRaises(SystemError, _socket.getnameinfo, (321), 8)
        self.assertRaises(TypeError, _socket.getnameinfo, ("127.0.0.1"), '0')
        self.assertRaises(TypeError, _socket.getnameinfo, ("127.0.0.1", 80, 0, 0, 0), 8)
        self.assertRaises(_socket.gaierror, _socket.getnameinfo, ('no such host will ever exist', 80), 8) 
Example #3
Source File: helpers.py    From panoptes with Apache License 2.0 6 votes vote down vote up
def resolve_hostnames(hostnames, timeout):
    """
    Do DNS resolution for a given list of hostnames

    This function uses gevent to resolve all the hostnames in *parallel*

    Args:
        hostnames (list): A list of strings
        timeout (int): The number of seconds to wait for resolution of **all** hostnames

    Returns:
        list: A list of (hostname, address) tuples in the same order as the input list of hostnames

    """
    assert validators.PanoptesValidators.valid_nonempty_iterable_of_strings(hostnames), u'hostnames should be a list'
    assert validators.PanoptesValidators.valid_nonzero_integer(timeout), u'timeout should be an int greater than zero'

    jobs = [gevent.spawn(wrap_errors(gaierror, socket.gethostbyname), host) for host in hostnames]
    gevent.joinall(jobs, timeout=timeout)
    addresses = [job.value if not isinstance(job.get(), gaierror) else None for job in jobs]
    results = [(hostnames[i], result) for i, result in enumerate(addresses)]
    return results 
Example #4
Source File: resolver_ares.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
def gethostbyname_ex(self, hostname, family=AF_INET):
        if PY3:
            if isinstance(hostname, str):
                hostname = hostname.encode('idna')
            elif not isinstance(hostname, (bytes, bytearray)):
                raise TypeError('Expected es(idna), not %s' % type(hostname).__name__)
        else:
            if isinstance(hostname, text_type):
                hostname = hostname.encode('ascii')
            elif not isinstance(hostname, str):
                raise TypeError('Expected string, not %s' % type(hostname).__name__)

        while True:
            ares = self.ares
            try:
                waiter = Waiter(self.hub)
                ares.gethostbyname(waiter, hostname, family)
                result = waiter.get()
                if not result[-1]:
                    raise gaierror(-5, 'No address associated with hostname')
                return result
            except gaierror:
                if ares is self.ares:
                    raise
                # "self.ares is not ares" means channel was destroyed (because we were forked) 
Example #5
Source File: dig.py    From minemeld-core with Apache License 2.0 6 votes vote down vote up
def query(self, name, dnsclass, type_):
        if isinstance(name, unicode):
            name = name.encode('ascii')
        elif not isinstance(name, str):
            raise TypeError('Expected string, not %s' % type(name).__name__)

        while True:
            ares = self.ares
            try:
                waiter = Waiter(self.hub)
                ares.query(waiter, name, dnsclass, type_)
                result = waiter.get()

                return result

            except gaierror:
                if ares is self.ares:
                    raise 
Example #6
Source File: resolver_ares.py    From satori with Apache License 2.0 6 votes vote down vote up
def gethostbyname_ex(self, hostname, family=AF_INET):
        if PY3:
            if isinstance(hostname, str):
                hostname = hostname.encode('idna')
            elif not isinstance(hostname, (bytes, bytearray)):
                raise TypeError('Expected es(idna), not %s' % type(hostname).__name__)
        else:
            if isinstance(hostname, text_type):
                hostname = hostname.encode('ascii')
            elif not isinstance(hostname, str):
                raise TypeError('Expected string, not %s' % type(hostname).__name__)

        while True:
            ares = self.ares
            try:
                waiter = Waiter(self.hub)
                ares.gethostbyname(waiter, hostname, family)
                result = waiter.get()
                if not result[-1]:
                    raise gaierror(-5, 'No address associated with hostname')
                return result
            except gaierror:
                if ares is self.ares:
                    raise
                # "self.ares is not ares" means channel was destroyed (because we were forked) 
Example #7
Source File: resolver_ares.py    From PokemonGo-DesktopMap with MIT License 6 votes vote down vote up
def gethostbyname_ex(self, hostname, family=AF_INET):
        if PY3:
            if isinstance(hostname, str):
                hostname = hostname.encode('idna')
            elif not isinstance(hostname, (bytes, bytearray)):
                raise TypeError('Expected es(idna), not %s' % type(hostname).__name__)
        else:
            if isinstance(hostname, text_type):
                hostname = hostname.encode('ascii')
            elif not isinstance(hostname, str):
                raise TypeError('Expected string, not %s' % type(hostname).__name__)

        while True:
            ares = self.ares
            try:
                waiter = Waiter(self.hub)
                ares.gethostbyname(waiter, hostname, family)
                result = waiter.get()
                if not result[-1]:
                    raise gaierror(-5, 'No address associated with hostname')
                return result
            except gaierror:
                if ares is self.ares:
                    raise
                # "self.ares is not ares" means channel was destroyed (because we were forked) 
Example #8
Source File: test__socket.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_getnameinfo(self):
        '''Tests _socket.getnameinfo()'''
        #sanity
        _socket.getnameinfo(("127.0.0.1", 80), 8)
        _socket.getnameinfo(("127.0.0.1", 80), 9)

        host, service = _socket.getnameinfo( ("127.0.0.1", 80), 8)
        self.assertEqual(service, '80')

        host, service = _socket.getnameinfo( ("127.0.0.1", 80), 0)
        self.assertEqual(service, "http")
        #IP gives a TypeError
        #self.assertRaises(SystemError, _socket.getnameinfo, ("127.0.0.1"), 8)
        #self.assertRaises(SystemError, _socket.getnameinfo, (321), 8)
        self.assertRaises(TypeError, _socket.getnameinfo, ("127.0.0.1"), '0')
        self.assertRaises(TypeError, _socket.getnameinfo, ("127.0.0.1", 80, 0, 0, 0), 8)
        self.assertRaises(_socket.gaierror, _socket.getnameinfo, ('no such host will ever exist', 80), 8) 
Example #9
Source File: ssh.py    From netman with Apache License 2.0 6 votes vote down vote up
def _open_channel(self, host, port, username, password, connect_timeout):
        self.client = paramiko.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            self.client.connect(host,
                                port=port,
                                username=username,
                                password=password,
                                timeout=connect_timeout,
                                allow_agent=False,
                                look_for_keys=False)
        except timeout:
            raise ConnectTimeout(host, port)
        except gaierror:
            raise CouldNotConnect(host, port)

        self.channel = self.client.invoke_shell()

        self._wait_for(self.prompt) 
Example #10
Source File: resolver_ares.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
        while True:
            ares = self.ares
            try:
                return self._getaddrinfo(host, port, family, socktype, proto, flags)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #11
Source File: resolver_ares.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def gethostbyaddr(self, ip_address):
        ip_address = _resolve_special(ip_address, AF_UNSPEC)
        while True:
            ares = self.ares
            try:
                return self._gethostbyaddr(ip_address)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #12
Source File: resolver_ares.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def gethostbyaddr(self, ip_address):
        ip_address = _resolve_special(ip_address, AF_UNSPEC)
        while True:
            ares = self.ares
            try:
                return self._gethostbyaddr(ip_address)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #13
Source File: resolver_ares.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def getnameinfo(self, sockaddr, flags):
        while True:
            ares = self.ares
            try:
                return self._getnameinfo(sockaddr, flags)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #14
Source File: run_autoresponder.py    From python-email-autoresponder with MIT License 5 votes vote down vote up
def connect_to_imap():
    try:
        do_connect_to_imap()
    except gaierror:
        shutdown_with_error("IMAP connection failed! Specified host not found.")
    except imaplib.IMAP4_SSL.error as e:
        shutdown_with_error("IMAP login failed! Reason: '" + cast(e.args[0], str, 'UTF-8') + "'.")
    except Exception as e:
        shutdown_with_error("IMAP connection/login failed! Reason: '" + cast(e, str) + "'.") 
Example #15
Source File: run_autoresponder.py    From python-email-autoresponder with MIT License 5 votes vote down vote up
def connect_to_smtp():
    try:
        do_connect_to_smtp()
    except gaierror:
        shutdown_with_error("SMTP connection failed! Specified host not found.")
    except smtplib.SMTPAuthenticationError as e:
        shutdown_with_error("SMTP login failed! Reason: '" + cast(e.smtp_error, str, 'UTF-8') + "'.")
    except Exception as e:
        shutdown_with_error("SMTP connection/login failed! Reason: '" + cast(e, str) + "'.") 
Example #16
Source File: resolver_thread.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def __init__(self, hub=None):
        if hub is None:
            hub = get_hub()
        self.pool = hub.threadpool
        if _socket.gaierror not in hub.NOT_ERROR:
            # Do not cause lookup failures to get printed by the default
            # error handler. This can be very noisy.
            hub.NOT_ERROR += (_socket.gaierror, _socket.herror) 
Example #17
Source File: resolver_ares.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
        while True:
            ares = self.ares
            try:
                return self._getaddrinfo(host, port, family, socktype, proto, flags)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #18
Source File: resolver_ares.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def gethostbyaddr(self, ip_address):
        ip_address = _resolve_special(ip_address, AF_UNSPEC)
        while True:
            ares = self.ares
            try:
                return self._gethostbyaddr(ip_address)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #19
Source File: resolver_thread.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def __init__(self, hub=None):
        if hub is None:
            hub = get_hub()
        self.pool = hub.threadpool
        if _socket.gaierror not in hub.NOT_ERROR:
            # Do not cause lookup failures to get printed by the default
            # error handler. This can be very noisy.
            hub.NOT_ERROR += (_socket.gaierror, _socket.herror) 
Example #20
Source File: resolver_ares.py    From PokemonGo-DesktopMap with MIT License 5 votes vote down vote up
def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
        while True:
            ares = self.ares
            try:
                return self._getaddrinfo(host, port, family, socktype, proto, flags)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #21
Source File: resolver_ares.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def gethostbyname_ex(self, hostname, family=AF_INET):
        if PY3:
            if isinstance(hostname, str):
                hostname = hostname.encode('idna')
            elif not isinstance(hostname, (bytes, bytearray)):
                raise TypeError('Expected es(idna), not %s' % type(hostname).__name__)
        else:
            if isinstance(hostname, text_type):
                hostname = hostname.encode('ascii')
            elif not isinstance(hostname, str):
                raise TypeError('Expected string, not %s' % type(hostname).__name__)

        while True:
            ares = self.ares
            try:
                waiter = Waiter(self.hub)
                ares.gethostbyname(waiter, hostname, family)
                result = waiter.get()
                if not result[-1]:
                    raise gaierror(-5, 'No address associated with hostname')
                return result
            except gaierror:
                if ares is self.ares:
                    if hostname == b'255.255.255.255':
                        # The stdlib handles this case in 2.7 and 3.x, but ares does not.
                        # It is tested by test_socket.py in 3.4.
                        # HACK: So hardcode the expected return.
                        return ('255.255.255.255', [], ['255.255.255.255'])
                    raise
                # "self.ares is not ares" means channel was destroyed (because we were forked) 
Example #22
Source File: resolver_thread.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def __init__(self, hub=None):
        if hub is None:
            hub = get_hub()
        self.pool = hub.threadpool
        if _socket.gaierror not in hub.NOT_ERROR:
            # Do not cause lookup failures to get printed by the default
            # error handler. This can be very noisy.
            hub.NOT_ERROR += (_socket.gaierror, _socket.herror) 
Example #23
Source File: telnet.py    From netman with Apache License 2.0 5 votes vote down vote up
def _connect(self):
        try:
            telnet = telnetlib.Telnet(self.host, self.port, self.connect_timeout)
        except timeout:
            raise ConnectTimeout(self.host, self.port)
        except gaierror:
            raise CouldNotConnect(self.host, self.port)

        telnet.set_option_negotiation_callback(_accept_all)
        return telnet 
Example #24
Source File: test__socket.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_gethostbyname_ex(self):
        '''Tests _socket.gethostbyname_ex'''
        #sanity
        joe = _socket.gethostbyname_ex("localhost")[2]
        self.assertIn("127.0.0.1" , joe)
        joe = _socket.gethostbyname_ex("127.0.0.1")[2]
        self.assertIn("127.0.0.1", joe)

        #negative
        self.assertRaises(_socket.gaierror, _socket.gethostbyname_ex, "should never work") 
Example #25
Source File: test__socket.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_gethostbyname(self):
        '''Tests _socket.gethostbyname'''
        #sanity
        self.assertEqual(_socket.gethostbyname("localhost"), "127.0.0.1")
        self.assertEqual(_socket.gethostbyname("127.0.0.1"), "127.0.0.1")
        self.assertEqual(_socket.gethostbyname("<broadcast>"), "255.255.255.255")

        #negative
        self.assertRaises(_socket.gaierror, _socket.gethostbyname, "should never work") 
Example #26
Source File: resolver_ares.py    From satori with Apache License 2.0 5 votes vote down vote up
def gethostbyaddr(self, ip_address):
        ip_address = _resolve_special(ip_address, AF_UNSPEC)
        while True:
            ares = self.ares
            try:
                return self._gethostbyaddr(ip_address)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #27
Source File: resolver_ares.py    From satori with Apache License 2.0 5 votes vote down vote up
def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
        while True:
            ares = self.ares
            try:
                return self._getaddrinfo(host, port, family, socktype, proto, flags)
            except gaierror:
                if ares is self.ares:
                    raise 
Example #28
Source File: resolver_thread.py    From satori with Apache License 2.0 5 votes vote down vote up
def __init__(self, hub=None):
        if hub is None:
            hub = get_hub()
        self.pool = hub.threadpool
        if _socket.gaierror not in hub.NOT_ERROR:
            # Do not cause lookup failures to get printed by the default
            # error handler. This can be very noisy.
            hub.NOT_ERROR += (_socket.gaierror, _socket.herror) 
Example #29
Source File: wsgi.py    From OpenMTC with Eclipse Public License 1.0 5 votes vote down vote up
def _get_addr_info(self, host, family):
        self.logger.debug("Resolving %s", host)
        try:
            info = getaddrinfo(host, 0, family, SOCK_STREAM)
            return set(map(itemgetter(0), map(itemgetter(-1), info)))
        except gaierror as e:
            self.logger.error("Failed to resolve %s: %s", host, e)
            return set() 
Example #30
Source File: test__socket.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_gethostbyname_ex(self):
        '''Tests _socket.gethostbyname_ex'''
        #sanity
        joe = _socket.gethostbyname_ex("localhost")[2]
        self.assertTrue("127.0.0.1" in joe)
        joe = _socket.gethostbyname_ex("127.0.0.1")[2]
        self.assertTrue("127.0.0.1" in joe)
        
        #negative
        self.assertRaises(_socket.gaierror, _socket.gethostbyname_ex, "should never work")