Python socket.gethostbyaddr() Examples

The following are code examples for showing how to use socket.gethostbyaddr(). 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: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 2
Project: LGWebOSRemote   Author: klattimer   File: auth.py    MIT License 6 votes vote down vote up
def __init__(self, name, host):
        self.__clientKey = None
        self.__macAddress = None
        self.__name = name
        self.__handshake_done = False

        # Check if host is an IP address or hostname
        # Try to resolve the hostname
        try:
            socket.inet_aton(host)
            self.__ip = host
            self.__hostname = socket.gethostbyaddr(host)[0]
        except:
            self.__hostname = host
            self.__ip = socket.gethostbyname(host)

        if self.__macAddress is None and self.__ip is not None:
            self.__macAddress = self.__get_mac_address(self.__ip)

        super(LGTVAuth, self).__init__('ws://' + self.__ip + ':3000/', exclude_headers=["Origin"])
        self.__waiting_callback = self.__prompt 
Example 3
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except OSError:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except OSError:
            # Probably a similar problem as above; skip this test
            self.skipTest('name lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 4
Project: autopyfactory   Author: PanDAWMS   File: htcondorlib.py    Apache License 2.0 6 votes vote down vote up
def _address(hostname, port=None):
    """
    builds the final string to contact a remote collector or
    remote Schedd, as '<hostname>' or '<hostname>:<port>'
    :param string hostname: the hostname or IP address of the remote service
    :param int port: [optional] port for the remote service 
    """
    hostname = socket.gethostbyaddr(hostname)[0]
    if port:
        address = '%s:%s' %(hostname, port)
    else:
        address = hostname
    return address


# =============================================================================
#              C O L L E C T O R   &   S C H E D D 
# ============================================================================= 
Example 5
Project: devtools-parser   Author: WPO-Foundation   File: devtools_parser.py    Apache License 2.0 6 votes vote down vote up
def get_base_page_info(self, page_data):
        """Find the reverse-ip info for the base page"""
        domain = urlparse.urlsplit(page_data['final_url']).hostname
        try:
            import socket
            addr = socket.gethostbyname(domain)
            host = str(socket.gethostbyaddr(addr)[0])
            page_data['base_page_ip_ptr'] = host
        except Exception:
            pass
        # keep moving up the domain until we can get a NS record
        while domain is not None and 'base_page_dns_soa' not in page_data:
            try:
                import dns.resolver
                dns_servers = dns.resolver.query(domain, "NS")
                dns_server = str(dns_servers[0].target).strip('. ')
                page_data['base_page_dns_ns'] = dns_server
            except Exception:
                pass
            pos = domain.find('.')
            if pos > 0:
                domain = domain[pos + 1:]
            else:
                domain = None 
Example 6
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rsocket.py    MIT License 6 votes vote down vote up
def test_thread_safe_gethostbyaddr():
    py.test.skip("hits non-thread-safe issues with ll2ctypes")
    import threading
    nthreads = 10
    ip = '8.8.8.8'
    domain = gethostbyaddr(ip)[0]
    result = [0] * nthreads
    threads = [None] * nthreads
    lock = threading.Lock()
    def lookup_addr(ip, i):
        name, aliases, address_list = gethostbyaddr(ip, lock)
        if name == domain:
            result[i] += 1
    for i in range(nthreads):
        threads[i] = threading.Thread(target = lookup_addr, args=[ip, i])
        threads[i].start()
    for i in range(nthreads):
        threads[i].join()
    assert sum(result) == nthreads 
Example 7
Project: ironpython2   Author: IronLanguages   File: test_socket.py    Apache License 2.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 8
Project: open-recipe   Author: dspray95   File: unix.py    The Unlicense 6 votes vote down vote up
def addUTMPEntry(self, loggedIn=1):
        if not utmp:
            return
        ipAddress = self.avatar.conn.transport.transport.getPeer().host
        packedIp, = struct.unpack('L', socket.inet_aton(ipAddress))
        ttyName = self.ptyTuple[2][5:]
        t = time.time()
        t1 = int(t)
        t2 = int((t-t1) * 1e6)
        entry = utmp.UtmpEntry()
        entry.ut_type = loggedIn and utmp.USER_PROCESS or utmp.DEAD_PROCESS
        entry.ut_pid = self.pty.pid
        entry.ut_line = ttyName
        entry.ut_id = ttyName[-4:]
        entry.ut_tv = (t1, t2)
        if loggedIn:
            entry.ut_user = self.avatar.username
            entry.ut_host = socket.gethostbyaddr(ipAddress)[0]
            entry.ut_addr_v6 = (packedIp, 0, 0, 0)
        a = utmp.UtmpRecord(utmp.UTMP_FILE)
        a.pututline(entry)
        a.endutent()
        b = utmp.UtmpRecord(utmp.WTMP_FILE)
        b.pututline(entry)
        b.endutent() 
Example 9
Project: FuzzFlow   Author: talos-vulndev   File: helper.py    MIT License 6 votes vote down vote up
def register_host(self):
        print "[*] Trying to register the host..."
        platform_id = self.get_platform_id()
        arch_id = self.get_arch_id()
        mac = self.get_mac()
        hostname, alias_list, addr_list = socket.gethostbyaddr(self.get_default_ip())
        ip = addr_list[0]
        host_payload = {
            'name' : hostname,
            'mac' : mac,
            'ip' : ip,
            'platform_id': platform_id,
            'arch_id': arch_id
        }

        self.host = Rest.get_host_by_mac(mac)
        if self.host is not None:
            print "[!] Host with mac address %s has already been registered." % mac
            Rest.update_host(self.host['id'], host_payload)
        else:
            self.host = Rest.create_host(host_payload)

        return self.host 
Example 10
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 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 11
Project: Blockly-rduino-communication   Author: technologiescollege   File: test_socket.py    GNU General Public License v3.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except OSError:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except OSError:
            # Probably a similar problem as above; skip this test
            self.skipTest('name lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 12
Project: Yuki-Chan-The-Auto-Pentest   Author: Yukinoshita47   File: common.py    MIT License 6 votes vote down vote up
def ip2name(addr):
    if not ip2name.resolve:
        return addr
    try:
        if addr in ip2name.cache:
            return ip2name.cache[addr]
        # FIXME: Workaround Python bug
        # Need double try/except to catch the bug
        try:
            name = gethostbyaddr(addr)[0]
        except KeyboardInterrupt:
            raise
    except (socket_host_error, ValueError):
        name = addr
    except (socket_host_error, KeyboardInterrupt, ValueError):
        ip2name.resolve = False
        name = addr
    ip2name.cache[addr] = name
    return name 
Example 13
Project: gstatus   Author: gluster   File: network.py    GNU General Public License v3.0 6 votes vote down vote up
def ip_to_host(addr):
    """ convert an IP address to a host name, returning shortname and fqdn to the 
        caller
    """

    try:
        fqdn = socket.gethostbyaddr(addr)[0]
        shortname = fqdn.split('.')[0]
        if fqdn == shortname:
            fqdn = ""

    except:
        # can't resolve it, so default to the address given
        shortname = addr
        fqdn = ""

    return shortname, fqdn 
Example 14
Project: ITWSV   Author: penetrate2hack   File: common.py    MIT License 6 votes vote down vote up
def ip2name(addr):
    if not ip2name.resolve:
        return addr
    try:
        if addr in ip2name.cache:
            return ip2name.cache[addr]
        # FIXME: Workaround Python bug
        # Need double try/except to catch the bug
        try:
            name = gethostbyaddr(addr)[0]
        except KeyboardInterrupt:
            raise
    except (socket_host_error, ValueError):
        name = addr
    except (socket_host_error, KeyboardInterrupt, ValueError):
        ip2name.resolve = False
        name = addr
    ip2name.cache[addr] = name
    return name 
Example 15
Project: AdminShell   Author: mtask   File: tools.py    GNU General Public License v2.0 6 votes vote down vote up
def get_host(self, target):
        self.t = target
        if re.findall( r'[0-9]+(?:\.[0-9]+){3}', self.t):
            try:
                self.res = socket.gethostbyaddr(self.t)
                return self.res[0]         
            except socket.gaierror:
                return "Couldn't find any results for: " +str(self.t)
            except Exception as e:
                print e
        else:
            try:
                self.res = socket.gethostbyname(self.t)
                return self.res
            except socket.gaierror:
                return "Couldn't find any results for: " +str(self.t)
            except Exception as e:
                print e 
Example 16
Project: xunfeng   Author: ysrc   File: scan.py    GNU General Public License v3.0 6 votes vote down vote up
def ip2hostname(self, ip):
        try:
            hostname = socket.gethostbyaddr(ip)[0]
            return hostname
        except:
            pass
        try:
            query_data = "\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x20\x43\x4b\x41\x41" + \
                         "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41" + \
                         "\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x41\x00\x00\x21\x00\x01"
            dport = 137
            _s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            _s.settimeout(3)
            _s.sendto(query_data, (ip, dport))
            x = _s.recvfrom(1024)
            tmp = x[0][57:]
            _s.close()
            hostname = tmp.split("\x00", 2)[0].strip()
            hostname = hostname.split()[0]
            return hostname
        except:
            pass 
Example 17
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_socket.py    GNU General Public License v2.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except OSError:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except OSError:
            # Probably a similar problem as above; skip this test
            self.skipTest('name lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 18
Project: oss-ftp   Author: aliyun   File: test_socket.py    MIT License 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 19
Project: data-flow-graph   Author: macbre   File: pcap-to-data-flow.py    MIT License 6 votes vote down vote up
def normalize_host(ip):
	def resolve_host(ip):
		logger = logging.getLogger('resolve_host')

		try:
			hostname = gethostbyaddr(ip)[0]
		except herror as e:
			# socket.herror: [Errno 1] Unknown host
			logger.error("Unable to resolve %s: %s", ip, e)
			return ip

		hostname = hostname.split('.')[0]
		logger.info("%s is known as %s", ip, hostname)

		if not hostname.startswith('ap-') and not hostname.startswith('task-'):
			return hostname
		else:
			# ap-s200 -> ap-s*
			return re.sub(r'\d+$', '*', hostname)

	if ip not in hosts_cache:
		hosts_cache[ip] = resolve_host(ip)

	return hosts_cache[ip] 
Example 20
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def getHostname():
	host = None
	if len(os.name) > 2:
		host = os.uname()[1]
	if not host:
		try:
			host = socket.gethostname()
			#host = socket.gethostbyaddr(socket.gethostname())[0]
		except:
			host = "unknown"
	return host

#===================== 
Example 21
Project: Old-school-processing   Author: cianfrocco-lab   File: apParam.py    MIT License 5 votes vote down vote up
def getHostIP(hostname=None):
	try:
		if hostname is None:
			hostname = socket.gethostname()
		ip = socket.gethostbyaddr(hostname)[2][0]
	except:
		ip = None
	return ip

#===================== 
Example 22
Project: job_manager   Author: lnls-fac   File: pyjob_server.py    MIT License 5 votes vote down vote up
def get_client_name(client):
    clientName = socket.gethostbyaddr(client.client_address[0])[0]
    if clientName == 'localhost':
        clientName = socket.gethostname()
    return clientName 
Example 23
Project: AvereSDK   Author: Azure   File: aws.py    MIT License 5 votes vote down vote up
def fqdn(self, instance):
        '''Provide the fully qualified domain name of the instance

            Arguments:
                instance: backend instance
        '''
        try:
            return socket.gethostbyaddr(instance.private_ip_address)[0]
        except Exception:
            return instance.private_dns_name

    # storage/buckets 
Example 24
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 25
Project: scopebuddy.py   Author: kronicd   File: scopebuddy.py    GNU General Public License v2.0 5 votes vote down vote up
def getRDNS(ip):
    """
        gets rdns, idk what you expect
    """
    try:
        data = socket.gethostbyaddr(ip)
        host = data[0]
        return host
    except Exception:
        # fail gracefully
        return "None"
# 
Example 26
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def test_host_resolution(self):
        for addr in [support.HOSTv4, '10.0.0.1', '255.255.255.255']:
            self.assertEqual(socket.gethostbyname(addr), addr)

        # we don't test support.HOSTv6 because there's a chance it doesn't have
        # a matching name entry (e.g. 'ip6-localhost')
        for host in [support.HOSTv4]:
            self.assertIn(host, socket.gethostbyaddr(host)[2]) 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def test_host_resolution_bad_address(self):
        # These are all malformed IP addresses and expected not to resolve to
        # any result.  But some ISPs, e.g. AWS, may successfully resolve these
        # IPs.
        explanation = (
            "resolving an invalid IP address did not raise OSError; "
            "can be caused by a broken DNS server"
        )
        for addr in ['0.1.1.~1', '1+.1.1.1', '::1q', '::1::2',
                     '1:1:1:1:1:1:1:1:1']:
            with self.assertRaises(OSError, msg=addr):
                socket.gethostbyname(addr)
            with self.assertRaises(OSError, msg=explanation):
                socket.gethostbyaddr(addr) 
Example 28
Project: NiujiaoDebugger   Author: MrSrc   File: test_socket.py    GNU General Public License v3.0 5 votes vote down vote up
def test_idna(self):
        # Check for internet access before running test
        # (issue #12804, issue #25138).
        with support.transient_internet('python.org'):
            socket.gethostbyname('python.org')

        # these should all be successful
        domain = 'испытание.pythontest.net'
        socket.gethostbyname(domain)
        socket.gethostbyname_ex(domain)
        socket.getaddrinfo(domain,0,socket.AF_UNSPEC,socket.SOCK_STREAM)
        # this may not work if the forward lookup chooses the IPv6 address, as that doesn't
        # have a reverse entry yet
        # socket.gethostbyaddr('испытание.python.org') 
Example 29
Project: threatdetectionservice   Author: flyballlabs   File: dynamic.py    Apache License 2.0 5 votes vote down vote up
def get_hostname():
    ''' Returns hostname of current host '''

    if socket.gethostname().find('.') >= 0:
        return socket.gethostname()
    else:
        return socket.gethostbyaddr(socket.gethostname())[0] 
Example 30
Project: pilot2   Author: PanDAWMS   File: tracereport.py    Apache License 2.0 5 votes vote down vote up
def init(self, job):
        """
        Initialization.

        :param job: job object.
        :return:
        """

        data = {
            'clientState': 'INIT_REPORT',
            'usr': hashlib.md5(job.produserid.encode('utf-8')).hexdigest(),  # anonymise user and pilot id's, Python 2/3
            'appid': job.jobid,
            'usrdn': job.produserid,
            'taskid': job.taskid
        }
        self.update(data)
        self['timeStart'] = time.time()

        try:
            self['hostname'] = socket.gethostbyaddr(socket.gethostname())[0]
        except Exception:
            logger.debug("unable to detect hostname for trace report")

        try:
            self['ip'] = socket.gethostbyname(socket.gethostname())
        except Exception:
            logger.debug("unable to detect host IP for trace report")

        if job.jobdefinitionid:
            s = 'ppilot_%s' % job.jobdefinitionid
            self['uuid'] = hashlib.md5(s.encode('utf-8')).hexdigest()  # hash_pilotid, Python 2/3
        else:
            #self['uuid'] = commands.getoutput('uuidgen -t 2> /dev/null').replace('-', '')  # all LFNs of one request have the same uuid
            cmd = 'uuidgen -t 2> /dev/null'
            exit_code, stdout, stderr = execute(cmd)
            self['uuid'] = stdout.replace('-', '') 
Example 31
Project: aiozk   Author: micro-fan   File: diag.py    MIT License 5 votes vote down vote up
def run():
    # await asyncio.sleep(10)
    logging.debug('Start')
    zk = ZKClient('zk', session_timeout=3)
    await zk.start()
    while 1:
        try:
            await zk.exists('/zookeeper')
            c = zk.session.conn
            ip = c.host_ip
            logging.debug('DIAG Curr conn: {}'.format([socket.gethostbyaddr(c.host_ip)[0]]))
        except Exception as e:
            logging.error('DIAG Exc: {}'.format(e))
        await asyncio.sleep(1) 
Example 32
Project: dionaea   Author: DinoTools   File: fieldtypes.py    GNU General Public License v2.0 5 votes vote down vote up
def resolve(self, x):
        if True:
            try:
                ret = socket.gethostbyaddr(x)[0]
            except:
                pass
            else:
                if ret:
                    return ret
        return x 
Example 33
Project: attacks-pages-collector   Author: ifreddyrondon   File: rules.emergingthreats.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 34
Project: attacks-pages-collector   Author: ifreddyrondon   File: malc0de.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 35
Project: attacks-pages-collector   Author: ifreddyrondon   File: malwaredomainlist.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 36
Project: attacks-pages-collector   Author: ifreddyrondon   File: autoshun.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 37
Project: attacks-pages-collector   Author: ifreddyrondon   File: map.norsecorp.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 38
Project: attacks-pages-collector   Author: ifreddyrondon   File: blocklist.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 39
Project: attacks-pages-collector   Author: ifreddyrondon   File: reputation.alienvault.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 40
Project: attacks-pages-collector   Author: ifreddyrondon   File: palevotracker.abuse.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 41
Project: attacks-pages-collector   Author: ifreddyrondon   File: openbl.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 42
Project: attacks-pages-collector   Author: ifreddyrondon   File: malwareblacklist.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 43
Project: attacks-pages-collector   Author: ifreddyrondon   File: nothink.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 44
Project: attacks-pages-collector   Author: ifreddyrondon   File: torstatus.blutmagie.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 45
Project: attacks-pages-collector   Author: ifreddyrondon   File: badips.py    MIT License 5 votes vote down vote up
def get_host(ip):
    attempts = 5
    host = "undefined"
    while attempts:
        try:
            data = socket.gethostbyaddr(ip)
            host = data[0]
            break
        except socket.herror:
            attempts -= 1

    return host 
Example 46
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rsocket.py    MIT License 5 votes vote down vote up
def test_gethostbyaddr():
    try:
        cpy_socket.gethostbyaddr("::1")
    except cpy_socket.herror:
        ipv6 = HSocketError
    except cpy_socket.gaierror:
        ipv6 = GAIError
    else:
        ipv6 = None
    for host in ["localhost", "127.0.0.1", "::1"]:
        if host == "::1" and ipv6:
            with py.test.raises(ipv6):
                gethostbyaddr(host)
            continue
        name, aliases, address_list = gethostbyaddr(host)
        allnames = [name] + aliases
        for n in allnames:
            assert isinstance(n, str)
        if sys.platform != 'win32':
            assert 'localhost' in allnames or 'ip6-localhost' in allnames
        for a in address_list:
            if isinstance(a, INETAddress) and a.get_host() == "127.0.0.1":
                break  # ok
            if host != '127.0.0.1':  # name lookup might return IPV6
                if isinstance(a, INET6Address) and a.get_host() == "::1":
                    break  # ok
        else:
            py.test.fail("could not find the localhost address in %r"
                         % (address_list,)) 
Example 47
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rsocket.py    MIT License 5 votes vote down vote up
def test_translate_netdb_lock():
    def f():
        rsocket_startup()
        gethostbyaddr("localhost")
        return 0
    fc = compile(f, [])
    assert fc() == 0 
Example 48
Project: rpython-lang-scheme   Author: tomoh1r   File: test_rsocket.py    MIT License 5 votes vote down vote up
def test_translate_netdb_lock_thread():
    def f():
        rsocket_startup()
        gethostbyaddr("localhost")
        return 0
    fc = compile(f, [], thread=True)
    assert fc() == 0 
Example 49
Project: lanscan   Author: sumpfgottheit   File: lanscan.py    MIT License 5 votes vote down vote up
def __init__(self, ip_address, mac_address):
        self.ip = ip_address
        self.mac = mac_address
        self.sort_value = netaddr.IPAddress(self.ip).value
        try:
            self.hostname = socket.gethostbyaddr(self.ip)[0]
        except socket.herror:
            # failed to resolve
            self.hostname = ''
        self.vendor = ''
        self.is_alive = False
        self.open_ports = {} 
Example 50
Project: TA-Send_to_HEC   Author: georgestarcher   File: net_utils.py    MIT License 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.')