Python socket.gethostbyname() Examples

The following are code examples for showing how to use socket.gethostbyname(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: charm-plumgrid-gateway   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 2
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def setOSCTarget(self, address, prefix=None, filters=None):
		"""Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
		  the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port
		    or a 'host' (string) : The host will be looked-up 
		  - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
		  sent to this OSCTarget (optional)
		"""
		if type(address) in str:
			address = self._searchHostAddr(address)
				
		elif (type(address) == tuple):
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except:
				pass
				
			address = (host, port)
		else:
			raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string")
		
		self._setTarget(address, prefix, filters) 
Example 3
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def delOSCTarget(self, address, prefix=None):
		"""Delete the specified OSCTarget from the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if type(address) == tuple:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			self._delTarget(address, prefix) 
Example 4
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def hasOSCTarget(self, address, prefix=None):
		"""Return True if the given OSCTarget exists in the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if type(address) == tuple:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			if address in list(self.targets.keys()):
				if prefix == None:
					return True
				elif prefix == self.targets[address][0]:
					return True
					
		return False 
Example 5
Project: pyOSC3   Author: Qirky   File: OSC3.py    (license) View Source Project 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in str:
			address = self._searchHostAddr(address) 

		if (type(address) == tuple): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in list(self.targets.keys())):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 6
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def setOSCTarget(self, address, prefix=None, filters=None):
		"""Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
		  the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port
		    or a 'host' (string) : The host will be looked-up 
		  - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
		  sent to this OSCTarget (optional)
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address)
				
		elif (type(address) == types.TupleType):
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except:
				pass
				
			address = (host, port)
		else:
			raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string")
		
		self._setTarget(address, prefix, filters) 
Example 7
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def delOSCTarget(self, address, prefix=None):
		"""Delete the specified OSCTarget from the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if type(address) == types.TupleType:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			self._delTarget(address, prefix) 
Example 8
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def hasOSCTarget(self, address, prefix=None):
		"""Return True if the given OSCTarget exists in the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the return-value is only True if the address and prefix match.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if type(address) == types.TupleType:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			if address in self.targets.keys():
				if prefix == None:
					return True
				elif prefix == self.targets[address][0]:
					return True
					
		return False 
Example 9
Project: pyOSC3   Author: Qirky   File: OSC2.py    (license) View Source Project 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if (type(address) == types.TupleType): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in self.targets.keys()):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 10
Project: python-   Author: secondtonone1   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 11
Project: cbapi-examples   Author: cbcommunity   File: sensor_backlog_aggregate.py    (MIT License) View Source Project 6 votes vote down vote up
def output(data, udp):
    """
    output the sensor backlog data, in JSON format
    always output to stdout
    output to udp if so specified
    """
    print data

    if udp is None:
        return

    try:
        sockaddr_components = udp.split(':')
        ip = socket.gethostbyname(sockaddr_components[0])
        port = int(sockaddr_components[1])
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        sock.sendto(data + '\n', (ip, port))
    except Exception, e:
        print e

    return 
Example 12
Project: cbapi-examples   Author: cbcommunity   File: sensor_backlog_individual.py    (MIT License) View Source Project 6 votes vote down vote up
def output(data, udp):
    """
    output the sensor backlog data, in JSON format
    always output to stdout
    output to udp if so specified
    """
    print data

    if udp is None:
        return

    try:
        sockaddr_components = udp.split(':')
        ip = socket.gethostbyname(sockaddr_components[0])
        port = int(sockaddr_components[1])
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        sock.sendto(data + '\n', (ip, port))
    except Exception, e:
        print e

    return 
Example 13
Project: my-first-blog   Author: AnkurBegining   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host).lower()

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 14
Project: my-first-blog   Author: AnkurBegining   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 15
Project: core-framework   Author: RedhawkSDR   File: io_helpers.py    (license) View Source Project 6 votes vote down vote up
def getStreamDef( self, name=None, hostip=None, pkts=1000, block=True, returnSddsAnalyzer=True):
        # grab data if stream definition is available 
        sdef =None
        aid=name
        if not aid:
            if len(self._streamdefs) ==  0:
                raise Exception("No attachment have been made, use grabData or call attach")
            
            aid = self._streamdefs.keys()[0]
            print "Defaults to first entry, attach id = ", aid
            sdef = self._streamdefs[aid]
        else:
            sdef = sefl._streamdefs[aid]
            
        if not sdef:
            raise Exception("No SDDS stream definition for attach id:" + aid )
        
        if not hostip:
            hostip = _socket.gethostbyname(_socket.gethostname())

        return self.getData( sdef.multicastAddress, hostip, sdef.port, packets, block=block, returnSDDSAnalyzer=returnSDDSAnalyzer) 
Example 16
Project: charm-swift-proxy   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 17
Project: charm-swift-proxy   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 18
Project: HeaTDV4A   Author: HeaTTheatR   File: multipartform.py    (license) View Source Project 6 votes vote down vote up
def choose_boundary():
    global _prefix

    if _prefix is None:
        hostid = socket.gethostbyname(socket.gethostname())

        try:
            uid = `os.getuid()`
        except:
            uid = '1'
        try:
            pid = `os.getpid()`
        except:
            pid = '1'

        _prefix = hostid + '.' + uid + '.' + pid

    timestamp = '%.3f' % time.time()
    seed = `random.randint(0, 32767)`
    return _prefix + '.' + timestamp + '.' + seed 
Example 19
Project: kinect-2-libras   Author: inessadl   File: mimetools.py    (Apache License 2.0) View Source Project 6 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 20
Project: cbapi-python   Author: carbonblack   File: sensor_backlog_aggregate.py    (license) View Source Project 6 votes vote down vote up
def output(data, udp):
    """
    output the sensor backlog data, in JSON format
    always output to stdout
    output to udp if so specified
    """
    print data

    if udp is None:
        return

    try:
        sockaddr_components = udp.split(':')
        ip = socket.gethostbyname(sockaddr_components[0])
        port = int(sockaddr_components[1])
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        sock.sendto(data + '\n', (ip, port))
    except Exception, e:
        print e

    return 
Example 21
Project: cbapi-python   Author: carbonblack   File: sensor_backlog_individual.py    (license) View Source Project 6 votes vote down vote up
def output(data, udp):
    """
    output the sensor backlog data, in JSON format
    always output to stdout
    output to udp if so specified
    """
    print data

    if udp is None:
        return

    try:
        sockaddr_components = udp.split(':')
        ip = socket.gethostbyname(sockaddr_components[0])
        port = int(sockaddr_components[1])
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
        sock.sendto(data + '\n', (ip, port))
    except Exception, e:
        print e

    return 
Example 22
Project: googletranslate.popclipext   Author: wizyoung   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host).lower()

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 23
Project: PyFlooder   Author: D4Vinci   File: pyflooder.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def attack():

    ip = socket.gethostbyname( host )
    global n
    msg=str(string.letters+string.digits+string.punctuation)
    data="".join(random.sample(msg,5))
    dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        n+=1
        dos.connect((ip, port))
        dos.send( "GET /%s HTTP/1.1\r\n" % data )
        print "\n "+time.ctime().split(" ")[3]+" "+"["+str(n)+"] #-#-# Hold Your Tears #-#-#"

    except socket.error:
        print "\n [ No connection! Server maybe down ] "

    dos.close() 
Example 24
Project: Projects   Author: it2school   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host).lower()

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 25
Project: Flask_Blog   Author: sugarguo   File: connectionpool.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 26
Project: pip-update-requirements   Author: alanhamlett   File: connectionpool.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host).lower()

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 27
Project: aws-waf-security-automation   Author: cerbo   File: connectionpool.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 28
Project: shadowsocksR-b   Author: hao35954514   File: mujson_mgr.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def getipaddr(self, ifname='eth0'):
		import socket
		import struct
		ret = '127.0.0.1'
		try:
			ret = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
		except:
			pass
		if ret == '127.0.0.1':
			try:
				import fcntl
				s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
				ret = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
			except:
				pass
		return ret 
Example 29
Project: charm-heat   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 30
Project: charm-keystone   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 31
Project: charm-keystone   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 32
Project: charm-keystone   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 33
Project: charm-keystone   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 34
Project: rex   Author: shellphish   File: linux_amd64_connectback.py    (license) View Source Project 6 votes vote down vote up
def to_raw(self, host, port):
        #pylint:disable=arguments-differ
        '''
        :param ip: string representing the ip address or domain name to connect back to
        :param port: port to connect to on the remote host
        '''

        l.debug("Connecting back to %s:%d", host, port)

        target_ip = socket.gethostbyname(host)
        raw_ip = socket.inet_aton(target_ip).encode('hex')

        if port < 0 or port >= 65535:
            raise ValueError("invalid port specified")

        raw_port = struct.pack("!H", port).encode('hex')

        return (self.hex_code % (raw_port, raw_ip)).decode('hex') 
Example 35
Project: rex   Author: shellphish   File: linux_x86_connectback.py    (license) View Source Project 6 votes vote down vote up
def to_raw(self, host, port):
        #pylint:disable=arguments-differ
        '''
        :param ip: string representing the ip address or domain name to connect back to
        :param port: port to connect to on the remote host
        '''

        l.debug("Connecting back to %s:%d", host, port)

        target_ip = socket.gethostbyname(host)
        raw_ip = socket.inet_aton(target_ip).encode('hex')

        if port < 0 or port >= 65535:
            raise ValueError("invalid port specified")

        raw_port = struct.pack("!H", port).encode('hex')

        return (self.hex_code % (raw_ip, raw_port)).decode('hex') 
Example 36
Project: swjtu-pyscraper   Author: Desgard   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 37
Project: charm-nova-cloud-controller   Author: openstack   File: ip.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def get_host_ip(hostname, fallback=None):
    """
    Resolves the IP for a given hostname, or returns
    the input if it is already an IP.
    """
    if is_ip(hostname):
        return hostname

    ip_addr = ns_query(hostname)
    if not ip_addr:
        try:
            ip_addr = socket.gethostbyname(hostname)
        except Exception:
            log("Failed to resolve hostname '%s'" % (hostname),
                level=WARNING)
            return fallback
    return ip_addr 
Example 38
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 39
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 40
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 41
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 42
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 43
Project: thorn   Author: robinhood   File: request.py    (license) View Source Project 6 votes vote down vote up
def to_safeurl(self, url):
        # type: (str) -> Tuple[str, str]
        parts = parse_url(url)
        host = parts.host
        addr = socket.gethostbyname(host)
        safeurl = Url(
            scheme=parts.scheme,
            auth=parts.auth,
            host=addr,
            port=parts.port,
            path=parts.path,
            query=parts.query,
            fragment=parts.fragment,
        )
        block_internal_ips()(addr)
        return host, safeurl.url 
Example 44
Project: jira_worklog_scanner   Author: pgarneau   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host).lower()

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 45
Project: jira_worklog_scanner   Author: pgarneau   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 46
Project: darkc0de-old-stuff   Author: tuwid   File: maxfr.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def handle_starttag(self, tag, attrs):

		tag = tag.lower()

		if tag == sequence[self.__s]: 
			self.__s += 1
			if self.__s == len(sequence):
				self.__s = 0
				for v in filter(lambda x: x[0]=='href',attrs):
		
					host = urlparse(v[1])[1]
					try:
						if self.__check and gethostbyname(host) != self.__q:
							continue
					except: continue

					if self.__callback: 
						self.__callback(host)
		else:
			self.__s = 0 
Example 47
Project: darkc0de-old-stuff   Author: tuwid   File: rwhois.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def _ParseWhois_Generic(self, fields):
        for field in fields:
            regex = "%s: *(.+)" % field['page_field']
            #print regex
            if field['rec_field'] == "servers":
                self.servers = []
                servers = re.findall(regex, self.page)
                for server in servers:
                    try:
                        server = string.strip(server)
                        ip = socket.gethostbyname(server)
                    except:
                        ip = "?"
                    self.servers.append((server, ip))
            else:
                m = re.search(regex, self.page)
                #if m: print m.group(1)
                if m: setattr(self, field['rec_field'], string.strip(m.group(1))) 
Example 48
Project: workflows.kyoyue   Author: wizyoung   File: connectionpool.py    (MIT License) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host).lower()

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 49
Project: CodingDojo   Author: ComputerSocietyUNB   File: base.py    (license) View Source Project 6 votes vote down vote up
def _check_query(self, query, country=False, city=False, city_or_country=False):
        "Helper routine for checking the query and database availability."
        # Making sure a string was passed in for the query.
        if not isinstance(query, six.string_types):
            raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__)

        # Extra checks for the existence of country and city databases.
        if city_or_country and not (self._country or self._city):
            raise GeoIP2Exception('Invalid GeoIP country and city data files.')
        elif country and not self._country:
            raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file)
        elif city and not self._city:
            raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file)

        # Return the query string back to the caller. GeoIP2 only takes IP addresses.
        if not (ipv4_re.match(query) or is_valid_ipv6_address(query)):
            query = socket.gethostbyname(query)

        return query 
Example 50
Project: zanph   Author: zanph   File: connectionpool.py    (license) View Source Project 6 votes vote down vote up
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port)