Python socket.gaierror() Examples

The following are code examples for showing how to use socket.gaierror(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    Apache License 2.0 6 votes vote down vote up
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if ':' in host and hasattr(socket, 'AF_INET6'):
        return socket.AF_INET6
    return socket.AF_INET 
Example 2
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: serving.py    Apache License 2.0 6 votes vote down vote up
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if ':' in host and hasattr(socket, 'AF_INET6'):
        return socket.AF_INET6
    return socket.AF_INET 
Example 3
Project: flasky   Author: RoseOu   File: serving.py    MIT License 6 votes vote down vote up
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if ':' in host and hasattr(socket, 'AF_INET6'):
        return socket.AF_INET6
    return socket.AF_INET 
Example 4
Project: smbprotocol   Author: jborean93   File: transport.py    MIT License 6 votes vote down vote up
def socket_connect(func):
    def wrapped(self, *args, **kwargs):
        if not self._connected:
            log.info("Connecting to DirectTcp socket")
            try:
                self._sock = socket.create_connection((self.server, self.port), timeout=self.timeout)
            except (OSError, socket.gaierror) as err:
                raise ValueError("Failed to connect to '%s:%s': %s" % (self.server, self.port, str(err)))
            self._sock.settimeout(None)  # Make sure the socket is in blocking mode.

            self._t_recv = threading.Thread(target=self.recv_thread, name="recv-%s:%s" % (self.server, self.port))
            self._t_recv.daemon = True
            self._t_recv.start()
            self._connected = True

        func(self, *args, **kwargs)

    return wrapped 
Example 5
Project: tornado-zh   Author: tao12345666333   File: netutil.py    MIT License 6 votes vote down vote up
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
Example 6
Project: tornado-zh   Author: tao12345666333   File: simple_httpclient_test.py    MIT License 6 votes vote down vote up
def test_ipv6(self):
        try:
            [sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
            port = sock.getsockname()[1]
            self.http_server.add_socket(sock)
        except socket.gaierror as e:
            if e.args[0] == socket.EAI_ADDRFAMILY:
                # python supports ipv6, but it's not configured on the network
                # interface, so skip this test.
                return
            raise
        url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)

        # ipv6 is currently enabled by default but can be disabled
        self.http_client.fetch(url, self.stop, allow_ipv6=False)
        response = self.wait()
        self.assertEqual(response.code, 599)

        self.http_client.fetch(url, self.stop)
        response = self.wait()
        self.assertEqual(response.body, b"Hello world!") 
Example 7
Project: tornado-zh   Author: tao12345666333   File: netutil.py    MIT License 6 votes vote down vote up
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
Example 8
Project: tornado-zh   Author: tao12345666333   File: simple_httpclient_test.py    MIT License 6 votes vote down vote up
def test_ipv6(self):
        try:
            [sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
            port = sock.getsockname()[1]
            self.http_server.add_socket(sock)
        except socket.gaierror as e:
            if e.args[0] == socket.EAI_ADDRFAMILY:
                # python supports ipv6, but it's not configured on the network
                # interface, so skip this test.
                return
            raise
        url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)

        # ipv6 is currently enabled by default but can be disabled
        self.http_client.fetch(url, self.stop, allow_ipv6=False)
        response = self.wait()
        self.assertEqual(response.code, 599)

        self.http_client.fetch(url, self.stop)
        response = self.wait()
        self.assertEqual(response.body, b"Hello world!") 
Example 9
Project: TornadoWeb   Author: VxCoder   File: netutil.py    Apache License 2.0 6 votes vote down vote up
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True 
Example 10
Project: sagemaker-xgboost-container   Author: aws   File: tracker.py    Apache License 2.0 6 votes vote down vote up
def get_host_ip(hostIP=None):
    if hostIP is None or hostIP == 'auto':
        hostIP = 'ip'

    if hostIP == 'dns':
        hostIP = socket.getfqdn()
    elif hostIP == 'ip':
        from socket import gaierror
        try:
            hostIP = socket.gethostbyname(socket.getfqdn())
        except gaierror:
            logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
            hostIP = socket.gethostbyname(socket.gethostname())
        if hostIP.startswith("127."):
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # doesn't have to be reachable
            s.connect(('10.255.255.255', 1))
            hostIP = s.getsockname()[0]
    return hostIP 
Example 11
Project: Flask_Blog   Author: sugarguo   File: serving.py    GNU General Public License v3.0 6 votes vote down vote up
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if ':' in host and hasattr(socket, 'AF_INET6'):
        return socket.AF_INET6
    return socket.AF_INET 
Example 12
Project: ProxHTTPSProxyMII   Author: wheever   File: ProxyTool.py    MIT License 6 votes vote down vote up
def tunnel_traffic(self):
        "Tunnel traffic to remote host:port"
        logger.info("%03d " % self.reqNum + Fore.CYAN + '[D] SSL Pass-Thru: https://%s/' % self.path)
        server_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            server_conn.connect((self.host, int(self.port)))
            self.wfile.write(("HTTP/1.1 200 Connection established\r\n" +
                              "Proxy-agent: %s\r\n" % self.version_string() +
                              "\r\n").encode('ascii'))
            read_write(self.connection, server_conn)
        except TimeoutError:
            self.wfile.write(b"HTTP/1.1 504 Gateway Timeout\r\n\r\n")
            logger.warning("%03d " % self.reqNum + Fore.YELLOW + 'Timed Out: https://%s:%s/' % (self.host, self.port))
        except socket.gaierror as e:
            self.wfile.write(b"HTTP/1.1 503 Service Unavailable\r\n\r\n")
            logger.warning("%03d " % self.reqNum + Fore.YELLOW + '%s: https://%s:%s/' % (e, self.host, self.port))
        finally:
            # We don't maintain a connection reuse pool, so close the connection anyway
            server_conn.close() 
Example 13
Project: redis-marshal   Author: mitjafelicijan   File: test_adjustments.py    MIT License 6 votes vote down vote up
def _hasIPv6(self): # pragma: nocover
        if not socket.has_ipv6:
            return False

        try:
            socket.getaddrinfo(
                '::1',
                0,
                socket.AF_UNSPEC,
                socket.SOCK_STREAM,
                socket.IPPROTO_TCP,
                socket.AI_PASSIVE | socket.AI_ADDRCONFIG
            )

            return True
        except socket.gaierror as e:
            # Check to see what the error is
            if e.errno == socket.EAI_ADDRFAMILY:
                return False
            else:
                raise e 
Example 14
Project: pyblish-win   Author: pyblish   File: mimetools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def choose_boundary():
    """Return a string usable as a multipart boundary.

    The string chosen is unique within a single program run, and
    incorporates the user id (if available), process id (if available),
    and current time.  So it's very unlikely the returned string appears
    in message text, but there's no guarantee.

    The boundary contains dots so you have to quote it in the header."""

    global _prefix
    import time
    if _prefix is None:
        import socket
        try:
            hostid = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            hostid = '127.0.0.1'
        try:
            uid = repr(os.getuid())
        except AttributeError:
            uid = '1'
        try:
            pid = repr(os.getpid())
        except AttributeError:
            pid = '1'
        _prefix = hostid + '.' + uid + '.' + pid
    return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())


# Subroutines for decoding some common content-transfer-types 
Example 15
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _safe_gethostbyname(host):
    try:
        return socket.gethostbyname(host)
    except socket.gaierror:
        return None 
Example 16
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
Example 17
Project: pyblish-win   Author: pyblish   File: urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def thishost():
    """Return the IP address of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            _thishost = socket.gethostbyname('localhost')
    return _thishost 
Example 18
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host='', port=0, local_hostname=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        """Initialize a new instance.

        If specified, `host' is the name of the remote host to which to
        connect.  If specified, `port' specifies the port to which to connect.
        By default, smtplib.SMTP_PORT is used.  If a host is specified the
        connect method is called, and if it returns anything other than a
        success code an SMTPConnectError is raised.  If specified,
        `local_hostname` is used as the FQDN of the local host for the
        HELO/EHLO command.  Otherwise, the local hostname is found using
        socket.getfqdn().

        """
        self.timeout = timeout
        self.esmtp_features = {}
        if host:
            (code, msg) = self.connect(host, port)
            if code != 220:
                raise SMTPConnectError(code, msg)
        if local_hostname is not None:
            self.local_hostname = local_hostname
        else:
            # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
            # if that can't be calculated, that we should use a domain literal
            # instead (essentially an encoded IP address like [A.B.C.D]).
            fqdn = socket.getfqdn()
            if '.' in fqdn:
                self.local_hostname = fqdn
            else:
                # We can't find an fqdn hostname, so use a domain literal
                addr = '127.0.0.1'
                try:
                    addr = socket.gethostbyname(socket.gethostname())
                except socket.gaierror:
                    pass
                self.local_hostname = '[%s]' % addr 
Example 19
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testSocketError(self):
        # Testing socket module exceptions
        def raise_error(*args, **kwargs):
            raise socket.error
        def raise_herror(*args, **kwargs):
            raise socket.herror
        def raise_gaierror(*args, **kwargs):
            raise socket.gaierror
        self.assertRaises(socket.error, raise_error,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_herror,
                              "Error raising socket exception.")
        self.assertRaises(socket.error, raise_gaierror,
                              "Error raising socket exception.") 
Example 20
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def testExceptionTree(self):
        self.assertTrue(issubclass(socket.error, Exception))
        self.assertTrue(issubclass(socket.herror, socket.error))
        self.assertTrue(issubclass(socket.gaierror, socket.error))
        self.assertTrue(issubclass(socket.timeout, socket.error)) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_urllibnet.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bad_address(self):
        # Make sure proper exception is raised when connecting to a bogus
        # address.
        bogus_domain = "sadflkjsasf.i.nvali.d"
        try:
            socket.gethostbyname(bogus_domain)
        except socket.gaierror:
            pass
        else:
            # This happens with some overzealous DNS providers such as OpenDNS
            self.skipTest("%r should not resolve for test to work" % bogus_domain)
        self.assertRaises(IOError,
                          # SF patch 809915:  In Sep 2003, VeriSign started
                          # highjacking invalid .com and .net addresses to
                          # boost traffic to their own site.  This test
                          # started failing then.  One hopes the .invalid
                          # domain will be spared to serve its defined
                          # purpose.
                          # urllib.urlopen, "http://www.sadflkjsasadf.com/")
                          urllib.urlopen, "http://sadflkjsasf.i.nvali.d/") 
Example 22
Project: OBS-ChatSpam   Author: dmadison   File: OBS_ChatSpam.py    GNU General Public License v3.0 5 votes vote down vote up
def __connect(self):
		if self.__connected:
			return True  # Already connected, nothing to see here

		self.__sock = socket.socket()
		self.__sock.settimeout(1)  # One second to connect

		try:
			self.__sock.connect((self.host, self.port))
		except socket.gaierror:
			return "Cannot find server"
		except (TimeoutError, socket.timeout):
			return "No response from server (connection timed out)"

		if self.password is not "":
			self.__sock.send("PASS {}\r\n".format(self.password).encode("utf-8"))
		self.__sock.send("NICK {}\r\n".format(self.nickname).encode("utf-8"))
		self.__sock.send("JOIN #{}\r\n".format(self.channel).encode("utf-8"))

		auth_response = self.read()
		if "Welcome, GLHF!" not in auth_response:
			return "Bad Authentication! Check your Oauth key"

		try:
			self.read()  # Wait for "JOIN" response
		except socket.timeout:
			return "Channel not found!"

		return True 
Example 23
Project: deep-learning-note   Author: wdxtub   File: 1_ftp_client.py    MIT License 5 votes vote down vote up
def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror) as e:
        print('ERROR: 无法连接 "{}"'.format(HOST))
        return
    print('*** 已连接到 "{}"'.format(HOST))

    try:
        f.login()
    except ftplib.error_perm:
        print('ERROR: 无法匿名登录')
        f.quit()
        return
    print('*** 已匿名身份登录')

    try:
        f.cwd(DIRN)
    except ftplib.error_perm:
        print('ERROR: 无法跳转到 "{}" 目录'.format(DIRN))
        f.quit()
        return
    print('*** 跳转到 "{}" 目录'.format(DIRN))

    try:
        f.retrbinary('RETR %s' % FILE, open(FILE, 'wb').write)
    except ftplib.error_perm:
        print('ERROR: 无法读取文件 "{}"'.format(FILE))
        os.unlink(FILE)
    else:
        print('*** 已下载 "{}" 到当前目录'.format(FILE))
    f.quit() 
Example 24
Project: whatwaff   Author: SVelizDonoso   File: whatwaff.py    MIT License 5 votes vote down vote up
def test_https(self, url):
        parsed = urlparse(url)
        protocol = parsed[0]
        hostname = parsed[1]
        path = parsed[2]
        sslerror = False
            
        conn = httplib.HTTPSConnection(hostname)
        try:
            conn.request('GET', '/')
            res = conn.getresponse()
        except socket.gaierror:
            return {'supported': False, 'certvalid': False}
        except ssl.CertificateError:
            return {'supported': True, 'certvalid': False}
        except:
            sslerror = True

        if sslerror:
            conn = httplib.HTTPSConnection(hostname, timeout=5, context = ssl._create_unverified_context() )
            try:
                conn.request('GET', '/')
                res = conn.getresponse()
                return {'supported': True, 'certvalid': False}
            except:
                return {'supported': False, 'certvalid': False}

        return {'supported': True, 'certvalid': True} 
Example 25
Project: whatwaff   Author: SVelizDonoso   File: whatwaff.py    MIT License 5 votes vote down vote up
def test_http_to_https(self, url, follow_redirects = 5):
        parsed = urlparse(url)
        protocol = parsed[0]
        hostname = parsed[1]
        path = parsed[2]
        if not protocol:
            protocol = 'http' 

        if protocol == 'https' and follow_redirects != 5:
            return True
        elif protocol == 'https' and follow_redirects == 5:
            protocol = 'http'

        if (protocol == 'http'):
            conn = httplib.HTTPConnection(hostname)
        try:
            conn.request('HEAD', path)
            res = conn.getresponse()
            headers = res.getheaders()
        except socket.gaierror:
            print '[*] Fallo la Solicitud HTTP '
            return False

       
        if (res.status >= 300 and res.status < 400  and follow_redirects > 0):
            for header in headers:
                if (header[0] == 'location'):
                    return self.test_http_to_https(header[1], follow_redirects - 1) 

        return False 
Example 26
Project: QuickScan   Author: NullArray   File: quickscan.py    GNU General Public License v3.0 5 votes vote down vote up
def scan(port):
		s = socket.socket()
		
		try:
			result = s.connect_ex((host,port))
		except socket.gaierror as e:
			if args.verbose == True:
				print "[" + t.red("!") + "]Critical. A GAIerror was raised with the following error message."
				print e 
				sys.exit(0)
			else:
				print "[" + t.red("!") + "]Critical. An error was raised while attempting to connect."
				sys.exit(0)
			
		if args.verbose == True:
			print "\n[" + t.green("+") + "]working on port: " + str(port)
			time.sleep(0.250)      
	
		if result == 0:
			counting_open.append(port)
			if args.verbose == True:
				print "\n[" + t.magenta("~") + "]" + str(port) + " -> open." 
				time.sleep(0.250)
			s.close()
		else:
			counting_close.append(port)
			if args.verbose == True:
				print "\n[" + t.magenta("~") + "]" + str(port) + " -> closed." 
				time.sleep(0.250)
			s.close() 
Example 27
Project: ipmisim   Author: rhtyd   File: fakesession.py    Apache License 2.0 5 votes vote down vote up
def _xmit_packet(self, retry=True, delay_xmit=None):
        if self.sequencenumber:
            self.sequencenumber += 1
        if delay_xmit is not None:
            # skip transmit, let retry timer do it's thing
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = delay_xmit +  _monotonic_time()
            return  
        if self.sockaddr:
            self.send_data(self.netpacket, self.sockaddr)
        else:
            self.allsockaddrs = []
            try:
                for res in socket.getaddrinfo(self.bmc, self.port, 0, socket.SOCK_DGRAM):
                    sockaddr = res[4]
                    if res[0] == socket.AF_INET:
                        # convert the sockaddr to AF_INET6
                        newhost = '::ffff:' + sockaddr[0]
                        sockaddr = (newhost, sockaddr[1], 0, 0)
                    self.allsockaddrs.append(sockaddr)
                    self.bmc_handlers[sockaddr] = self
                    self.send_data(self.netpacket, sockaddr)
            except socket.gaierror:
                raise exc.IpmiException("Unable to transmit to specified address")
        if retry:
            self.waiting_sessions[self] = {}
            self.waiting_sessions[self]['ipmisession'] = self
            self.waiting_sessions[self]['timeout'] = self.timeout + _monotonic_time() 
Example 28
Project: glazier   Author: google   File: ntp.py    Apache License 2.0 5 votes vote down vote up
def SyncClockToNtp(retries: int = 2, server: Text = 'time.google.com'):
  """Syncs the hardware clock to an NTP server."""
  logging.info('Reading time from NTP server %s.', server)

  attempts = 0
  client = ntplib.NTPClient()
  response = None

  while True:
    try:
      response = client.request(server, version=3)
    except (ntplib.NTPException, socket.gaierror) as e:
      logging.error('NTP client request error: %s', str(e))
    if response or attempts >= retries:
      break
    logging.info(
        'Unable to contact NTP server %s to sync machine clock.  This '
        'machine may not have an IP address yet; waiting %d seconds and '
        'trying again. Repeated failure may indicate network or driver '
        'problems.', server, RETRY_DELAY)
    time.sleep(RETRY_DELAY)
    attempts += 1

  if not response:
    raise NtpException('No response from NTP server.')

  local_time = time.localtime(response.ref_time)
  current_date = time.strftime('%m-%d-%Y', local_time)
  current_time = time.strftime('%H:%M:%S', local_time)
  logging.info('Current date/time is %s %s', current_date, current_time)

  date_set = r'%s\cmd.exe /c date %s' % (WINPE_SYSTEM32, current_date)
  result = subprocess.call(date_set, shell=True)
  logging.info('Setting date returned result %s', result)
  time_set = r'%s\cmd.exe /c time %s' % (WINPE_SYSTEM32, current_time)
  result = subprocess.call(time_set, shell=True)
  logging.info('Setting time returned result %s', result) 
Example 29
Project: jawfish   Author: war-and-code   File: support.py    MIT License 5 votes vote down vote up
def _is_ipv6_enabled():
    """Check whether IPv6 is enabled on this host."""
    if socket.has_ipv6:
        sock = None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            sock.bind(('::1', 0))
            return True
        except (socket.error, socket.gaierror):
            pass
        finally:
            if sock:
                sock.close()
    return False 
Example 30
Project: blobfile   Author: cshesse   File: ops.py    The Unlicense 5 votes vote down vote up
def _is_gce_instance() -> bool:
    try:
        socket.getaddrinfo("metadata.google.internal", 80)
    except socket.gaierror:
        return False
    return True 
Example 31
Project: Repobot   Author: Desgard   File: support.py    MIT License 5 votes vote down vote up
def _is_ipv6_enabled():
    """Check whether IPv6 is enabled on this host."""
    if socket.has_ipv6:
        sock = None
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            sock.bind(('::1', 0))
            return True
        except (socket.error, socket.gaierror):
            pass
        finally:
            if sock:
                sock.close()
    return False 
Example 32
Project: Repobot   Author: Desgard   File: request.py    MIT License 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
Example 33
Project: Repobot   Author: Desgard   File: request.py    MIT License 5 votes vote down vote up
def _safe_gethostbyname(host):
    try:
        return socket.gethostbyname(host)
    except socket.gaierror:
        return None 
Example 34
Project: Repobot   Author: Desgard   File: request.py    MIT License 5 votes vote down vote up
def thishost():
    """Return the IP addresses of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
        except socket.gaierror:
            _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
    return _thishost 
Example 35
Project: AvereSDK   Author: Azure   File: test_service.py    MIT License 5 votes vote down vote up
def test_gethostbyname(self):
        self.assertTrue(vFXT.service.gethostbyname('www.google.com'))
        self.assertTrue(vFXT.service.gethostbyname('127.0.0.1'))

        self.assertRaises(socket.gaierror, vFXT.service.gethostbyname, '-') 
Example 36
Project: AvereSDK   Author: Azure   File: service.py    MIT License 5 votes vote down vote up
def gethostbyname(host, timeout=DNS_TIMEOUT):
    '''Local gethostbyname that uses dns.resolver if available for fast timeouts
        Arguments:
            host (str): host name to resolve
            timeout (float): resolution timeout (defaults to vFXT.service.DNS_TIMEOUT)

        Raises: socket.gaierror
    '''
    try:
        from dns.resolver import Resolver
        import dns.inet #pylint: disable=import-outside-toplevel
        r = Resolver()
        r.timeout = r.lifetime = timeout

        # if this is an address, return ok
        try:
            addr = dns.inet.inet_pton(dns.inet.af_for_address(host), host)
            if addr:
                return host
        except Exception: pass

        try:
            return r.query(host)[0].to_text()
        except Exception as e:
            raise socket.gaierror(e)
    except ImportError:
        return socket.gethostbyname(host) 
Example 37
Project: AvereSDK   Author: Azure   File: service.py    MIT License 5 votes vote down vote up
def dns_check(cls, timeout=DNS_TIMEOUT):
        '''Verify name resolution to ENDPOINT_TEST_HOSTS

            Arguments:
                timeout (int, optional): defaults to vFXT.service.DNS_TIMEOUT
        '''
        try:
            for host in cls.ENDPOINT_TEST_HOSTS:
                gethostbyname(host, timeout)
        except socket.gaierror as e:
            raise vFXTConfigurationException("Failed to establish connection to service: {}".format(e)) 
Example 38
Project: osg-configure   Author: opensciencegrid   File: validation.py    Apache License 2.0 5 votes vote down vote up
def valid_domain(host, resolve=False):
    """Return True if the string passed in is a valid domain

    If resolve=True, also check that it resolves (according to gethostbyname).

    """
    if not host:
        return False
    is_ipv4_address = False
    try:
        is_ipv4_address = bool(socket.inet_pton(socket.AF_INET, host))
    except socket.error:
        pass
    is_ipv6_address = False
    try:
        is_ipv6_address = bool(socket.inet_pton(socket.AF_INET6, host))
    except socket.error:
        pass
    is_hostname = valid_hostname(host)

    if not (is_ipv4_address or is_ipv6_address or is_hostname):
        return False

    if not resolve:
        return True

    try:
        socket.gethostbyname(host)
    except (socket.herror, socket.gaierror):
        return False
    return True 
Example 39
Project: Reconbot   Author: dirk37   File: bot.py    MIT License 5 votes vote down vote up
def dnsquery(name: str):
    '''
    Convert a hostname to an IP address
    '''
    if sys.platform == 'win32':
        try:
            host = socket.gethostbyname(name)

            if host == name:
                await BOT.say('`{}` is already a valid IP Address'.format(name))
            else:
                await BOT.say('IP Address for `{}` is `{}`'.format(name, host))

            return host
        except socket.gaierror as err:
            await BOT.say('Error: {}'.format(err))
    else:
        try:
            ipaddress.ip_address(name)
            await BOT.say('`{}` is already a valid IP Address'.format(name))
            return name
        except ValueError:
            pass

        try:
            hosts = await DNS_RESOLVER.query(name, 'A')
            await BOT.say('IP Address for `{}` is `{}`'.format(name, hosts[0].host))
            return hosts[0].host
        except aiodns.error.DNSError as err:
            await BOT.say('Error: {}'.format(err.args[1])) 
Example 40
Project: misp42splunk   Author: remg427   File: net_utils.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def resolve_hostname(addr):
    '''Try to resolve an IP to a host name and returns None
    on common failures.

    :param addr: IP address to resolve.
    :type addr: ``string``
    :returns: Host name if success else None.
    :rtype: ``string``

    :raises ValueError: If `addr` is not a valid address
    '''

    if ip_math.is_valid_ip(addr):
        try:
            name, _, _ = socket.gethostbyaddr(addr)
            return name
        except socket.gaierror:
            # [Errno 8] nodename nor servname provided, or not known
            pass
        except socket.herror:
            # [Errno 1] Unknown host
            pass
        except socket.timeout:
            # Timeout.
            pass

        return None
    else:
        raise ValueError('Invalid ip address.') 
Example 41
Project: misp42splunk   Author: remg427   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _conn_request(self, conn, request_uri, method, body, headers):
        i = 0
        seen_bad_status_line = False
        while i < RETRIES:
            i += 1
            try:
                if hasattr(conn, 'sock') and conn.sock is None:
                    conn.connect()
                conn.request(method, request_uri, body, headers)
            except socket.timeout:
                raise
            except socket.gaierror:
                conn.close()
                raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
            except ssl_SSLError:
                conn.close()
                raise
            except socket.error, e:
                err = 0
                if hasattr(e, 'args'):
                    err = getattr(e, 'args')[0]
                else:
                    err = e.errno
                if err in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
                    continue  # retry on potentially transient socket errors
                raise
            except httplib.HTTPException:
                # Just because the server closed the connection doesn't apparently mean
                # that the server didn't send a response.
                if hasattr(conn, 'sock') and conn.sock is None:
                    if i < RETRIES-1:
                        conn.close()
                        conn.connect()
                        continue
                    else:
                        conn.close()
                        raise
                if i < RETRIES-1:
                    conn.close()
                    conn.connect()
                    continue 
Example 42
Project: tornado-zh   Author: tao12345666333   File: iostream_test.py    MIT License 5 votes vote down vote up
def test_gaierror(self):
        # Test that IOStream sets its exc_info on getaddrinfo error.
        # It's difficult to reliably trigger a getaddrinfo error;
        # some resolvers own't even return errors for malformed names,
        # so we mock it instead. If IOStream changes to call a Resolver
        # before sock.connect, the mock target will need to change too.
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
        stream = IOStream(s, io_loop=self.io_loop)
        stream.set_close_callback(self.stop)
        with mock.patch('socket.socket.connect',
                        side_effect=socket.gaierror('boom')):
            with ExpectLog(gen_log, "Connect error"):
                stream.connect(('localhost', 80), callback=self.stop)
                self.wait()
                self.assertIsInstance(stream.error, socket.gaierror) 
Example 43
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    MIT License 5 votes vote down vote up
def _failing_getaddrinfo(*args):
    """Dummy implementation of getaddrinfo for use in mocks"""
    raise socket.gaierror("mock: lookup failed") 
Example 44
Project: tornado-zh   Author: tao12345666333   File: netutil_test.py    MIT License 5 votes vote down vote up
def _failing_getaddrinfo(*args):
    """Dummy implementation of getaddrinfo for use in mocks"""
    raise socket.gaierror("mock: lookup failed") 
Example 45
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: DnsSpoof.py    GNU General Public License v3.0 5 votes vote down vote up
def listItemclicked(self,pos):
        item = self.myListDns.selectedItems()
        self.listMenu= QMenu()
        menu = QMenu()
        additem = menu.addAction('Add Host')
        removeitem = menu.addAction('Remove Host')
        clearitem = menu.addAction('clear all')
        action = menu.exec_(self.myListDns.viewport().mapToGlobal(pos))
        if action == removeitem:
            if item != []:
                self.myListDns.takeItem(self.myListDns.currentRow())
        elif action == additem:
            text, resp = QInputDialog.getText(self, 'Add DNS',
            'Enter the DNS and IP for spoof hosts: ex: example2.com')
            if resp:
                try:
                    itemsexits = []
                    for index in xrange(self.myListDns.count()):
                        itemsexits.append(str(self.myListDns.item(index).text()))
                    for i in itemsexits:
                        if search(str(text),i):
                            QMessageBox.information(self,'Dns Rsolver','this DNS already exist on List Attack')
                            return
                    item = QListWidgetItem()
                    item.setIcon(QIcon('Icons/dnsspoof.png'))
                    item.setText(text)
                    item.setSizeHint(QSize(30,30))
                    self.myListDns.addItem(item)
                except gaierror,e:
                    QMessageBox.information(self,'error',str(e))
                    return 
Example 46
Project: pysploit-framework   Author: ahmadnourallah   File: ip_gather.py    GNU General Public License v2.0 5 votes vote down vote up
def exploit():
    """ main exploit function """
    try:
        var = socket.gethostbyname(obtainer.options['target'][2])
        print(var)
    except socket.gaierror:
        print(Red + "Error:" + White + "You should enter right url.")
        return False 
Example 47
Project: analyzer-website   Author: santiagolizardo   File: __init__.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _conn_request(self, conn, request_uri, method, body, headers):
        for i in range(RETRIES):
            try:
                if hasattr(conn, 'sock') and conn.sock is None:
                    conn.connect()
                conn.request(method, request_uri, body, headers)
            except socket.timeout:
                raise
            except socket.gaierror:
                conn.close()
                raise ServerNotFoundError("Unable to find the server at %s" % conn.host)
            except ssl_SSLError:
                conn.close()
                raise
            except socket.error, e:
                err = 0
                if hasattr(e, 'args'):
                    err = getattr(e, 'args')[0]
                else:
                    err = e.errno
                if err == errno.ECONNREFUSED: # Connection refused
                    raise
            except httplib.HTTPException:
                # Just because the server closed the connection doesn't apparently mean
                # that the server didn't send a response.
                if hasattr(conn, 'sock') and conn.sock is None:
                    if i < RETRIES-1:
                        conn.close()
                        conn.connect()
                        continue
                    else:
                        conn.close()
                        raise
                if i < RETRIES-1:
                    conn.close()
                    conn.connect()
                    continue 
Example 48
Project: dcos-proxy   Author: dparrish   File: build-config.py    Apache License 2.0 4 votes vote down vote up
def main(argv):
    try:
        old_config = None
        while True:
            params = {
                'vhosts': {},
            }

            s = requests.Session()
            apps = json.loads(s.get('http://master.mesos:8080/v2/apps').text)
            for app in apps['apps']:
                try:
                    vhost = app['labels']['VIRTUAL_HOST']
                except KeyError:
                    continue
                tasks = json.loads(s.get('http://master.mesos:8080/v2/apps%s/tasks' % app['id'],
                                         headers={'Accept': 'application/json'}).text)
                backends = []
                for task in tasks['tasks']:
                    try:
                        ip = socket.gethostbyname(task['host'])
                    except socket.gaierror:
                        print "Can't look up host %s" % task['host']
                        continue
                    backends.append('%s:%s' % (ip, task['ports'][0]))
                if backends:
                    params['vhosts'][vhost] = {
                        'backends': backends,
                    }

            template = Template(TEMPLATE)
            new_config = template.render(params)
            if new_config != old_config:
                with file('/etc/nginx/sites-available/default', 'w') as fh:
                    fh.write(new_config)
                test = subprocess.Popen(['/usr/sbin/nginx', '-t'], stderr=subprocess.PIPE)
                output = test.communicate()
                if test.returncode != 0:
                    if old_config:
                        print 'Error generating new NGINX configuration, not reloading'
                        return
                    else:
                        raise RuntimeError('Error generating NGINX configuration')
                subprocess.call(['/usr/sbin/nginx', '-s', 'reload'])
                old_config = new_config
            time.sleep(10)
    except KeyboardInterrupt:
        return 1 
Example 49
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def testGetaddrinfo(self):
        try:
            socket.getaddrinfo('localhost', 80)
        except socket.gaierror as err:
            if err.errno == socket.EAI_SERVICE:
                # see http://bugs.python.org/issue1282647
                self.skipTest("buggy libc version")
            raise
        # len of every sequence is supposed to be == 5
        for info in socket.getaddrinfo(HOST, None):
            self.assertEqual(len(info), 5)
        # host can be a domain name, a string representation of an
        # IPv4/v6 address or None
        socket.getaddrinfo('localhost', 80)
        socket.getaddrinfo('127.0.0.1', 80)
        socket.getaddrinfo(None, 80)
        if SUPPORTS_IPV6:
            socket.getaddrinfo('::1', 80)
        # port can be a string service name such as "http", a numeric
        # port number (int or long), or None
        socket.getaddrinfo(HOST, "http")
        socket.getaddrinfo(HOST, 80)
        socket.getaddrinfo(HOST, 80L)
        socket.getaddrinfo(HOST, None)
        # test family and socktype filters
        infos = socket.getaddrinfo(HOST, None, socket.AF_INET)
        for family, _, _, _, _ in infos:
            self.assertEqual(family, socket.AF_INET)
        infos = socket.getaddrinfo(HOST, None, 0, socket.SOCK_STREAM)
        for _, socktype, _, _, _ in infos:
            self.assertEqual(socktype, socket.SOCK_STREAM)
        # test proto and flags arguments
        socket.getaddrinfo(HOST, None, 0, 0, socket.SOL_TCP)
        socket.getaddrinfo(HOST, None, 0, 0, 0, socket.AI_PASSIVE)
        # a server willing to support both IPv4 and IPv6 will
        # usually do this
        socket.getaddrinfo(None, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                           socket.AI_PASSIVE)

        # Issue 17269: test workaround for OS X platform bug segfault
        if hasattr(socket, 'AI_NUMERICSERV'):
            try:
                # The arguments here are undefined and the call may succeed
                # or fail.  All we care here is that it doesn't segfault.
                socket.getaddrinfo("localhost", None, 0, 0, 0,
                                   socket.AI_NUMERICSERV)
            except socket.gaierror:
                pass 
Example 50
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: utils.py    MIT License 4 votes vote down vote up
def should_bypass_proxies(url, no_proxy):
    """
    Returns whether we should bypass proxies or not.

    :rtype: bool
    """
    get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())

    # First check whether no_proxy is defined. If it is, check that the URL
    # we're getting isn't in the no_proxy list.
    no_proxy_arg = no_proxy
    if no_proxy is None:
        no_proxy = get_proxy('no_proxy')
    netloc = urlparse(url).netloc

    if no_proxy:
        # We need to check whether we match here. We need to see if we match
        # the end of the netloc, both with and without the port.
        no_proxy = (
            host for host in no_proxy.replace(' ', '').split(',') if host
        )

        ip = netloc.split(':')[0]
        if is_ipv4_address(ip):
            for proxy_ip in no_proxy:
                if is_valid_cidr(proxy_ip):
                    if address_in_network(ip, proxy_ip):
                        return True
                elif ip == proxy_ip:
                    # If no_proxy ip was defined in plain IP notation instead of cidr notation &
                    # matches the IP of the index
                    return True
        else:
            for host in no_proxy:
                if netloc.endswith(host) or netloc.split(':')[0].endswith(host):
                    # The URL does match something in no_proxy, so we don't want
                    # to apply the proxies on this URL.
                    return True

    # If the system proxy settings indicate that this URL should be bypassed,
    # don't proxy.
    # The proxy_bypass function is incredibly buggy on OS X in early versions
    # of Python 2.6, so allow this call to fail. Only catch the specific
    # exceptions we've seen, though: this call failing in other ways can reveal
    # legitimate problems.
    with set_environ('no_proxy', no_proxy_arg):
        try:
            bypass = proxy_bypass(netloc)
        except (TypeError, socket.gaierror):
            bypass = False

    if bypass:
        return True

    return False