Python socket.gethostbyaddr() Examples

The following are 30 code examples of socket.gethostbyaddr(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: common.py    From Yuki-Chan-The-Auto-Pentest with MIT License 7 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 #2
Source File: __init__.py    From webdigger with GNU General Public License v3.0 6 votes vote down vote up
def whois(url, command=False):
    # clean domain to expose netloc
    ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = result[0]
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain, 0)
    return WhoisEntry.load(domain, text) 
Example #3
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 6 votes vote down vote up
def _get_reverse_dns(ip_address):
    """
    Queries for an IP addresses reverse DNS hostname(s)

    Args:
        ip_address (str): An IPv4 or IPv6 address

    Returns:
        list: A list of reverse DNS hostnames

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        results = socket.gethostbyaddr(ip_address)
        hostnames = [results[0]] + results[1]
    except socket.herror:
        return []
    except Exception as error:
        raise DNSException(error)

    return hostnames 
Example #4
Source File: unix.py    From learn_python3_spider with MIT License 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 #5
Source File: test_socket.py    From ironpython2 with 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 #6
Source File: resolver.py    From script.elementum.burst with Do What The F*ck You Want To Public License 6 votes vote down vote up
def override_system_resolver(resolver=None):
    """Override the system resolver routines in the socket module with
    versions which use dnspython's resolver.

    This can be useful in testing situations where you want to control
    the resolution behavior of python code without having to change
    the system's resolver settings (e.g. /etc/resolv.conf).

    The resolver to use may be specified; if it's not, the default
    resolver will be used.

    @param resolver: the resolver to use
    @type resolver: dns.resolver.Resolver object or None
    """
    if resolver is None:
        resolver = get_default_resolver()
    global _resolver
    _resolver = resolver
    socket.getaddrinfo = _getaddrinfo
    socket.getnameinfo = _getnameinfo
    socket.getfqdn = _getfqdn
    socket.gethostbyname = _gethostbyname
    socket.gethostbyname_ex = _gethostbyname_ex
    socket.gethostbyaddr = _gethostbyaddr 
Example #7
Source File: test_socket.py    From ironpython3 with 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 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 #8
Source File: __init__.py    From Belati with GNU General Public License v2.0 6 votes vote down vote up
def whois(url, command=False):
    # clean domain to expose netloc
    ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = result[0]
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain, 0)
    return WhoisEntry.load(domain, text) 
Example #9
Source File: __init__.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def get_local_hostname(self):
        """
        Returns the local hostname under which the webinterface can be reached

        :return: fully qualified hostname
        :rtype: str
        """
        import socket
        try:
            return socket.gethostbyaddr(self.get_local_ip_address())[0] # can fail with default /etc/hosts
        except socket.herror:
            try:
                return socket.gethostbyaddr("127.0.1.1")[0]	# in debian based systems hostname is assigned to "127.0.1.1" by default
            except socket.herror:
                try:
                    return socket.gethostbyaddr("127.0.0.1")[0]	# 'localhost' in most cases
                except socket.herror:
                    return "localhost"	# should not happen 
Example #10
Source File: auth.py    From LGWebOSRemote with 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 #11
Source File: scan_gethostname.py    From apt2 with MIT License 6 votes vote down vote up
def process(self):
        # load any targets we are interested in
        self.getTargets()

        # loop over each target
        for t in self.targets:
            # verify we have not tested this host before
            if not self.seentarget(t):
                # add the new IP to the already seen list
                self.addseentarget(t)
                self.display.verbose(self.shortName + " - Connecting to " + t)
                try:
                    results = socket.gethostbyaddr(t)
                    self.fire("newHostname")
                    kb.add('host/' + t + '/hostname/' + results[0])
                except:
                    pass

        return 
Example #12
Source File: __init__.py    From whois with MIT License 6 votes vote down vote up
def whois(url, command=False, flags=0):
    # clean domain to expose netloc
    ip_match = IPV4_OR_V6.match(url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = extract_domain(result[0])
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read().decode()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain.encode('idna'), flags)
    return WhoisEntry.load(domain, text) 
Example #13
Source File: network.py    From gstatus with 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
Source File: common.py    From ITWSV with 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
Source File: unix.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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 #16
Source File: test_socket.py    From Fluid-Designer with 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 #17
Source File: scan.py    From xunfeng with 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 #18
Source File: test_socket.py    From BinderFilter with 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
            return
        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
            return
        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
Source File: output_handler.py    From honssh with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def port_forward_log(self, channel_name, conn_details):
        the_dns = ''
        try:
            the_dns = ' (' + socket.gethostbyaddr(conn_details['srcIP'])[0] + ')'
        except:
            pass
        # TODO: LOG SOMEWHERE
        log.msg(log.LPURPLE, '[OUTPUT]',
                channel_name + ' Source: ' + conn_details['srcIP'] + ':' + str(conn_details['srcPort']) + the_dns)

        the_dns = ''
        try:
            the_dns = ' (' + socket.gethostbyaddr(conn_details['dstIP'])[0] + ')'
        except:
            pass
        # TODO: LOG SOMEWHERE
        log.msg(log.LPURPLE, '[OUTPUT]',
                channel_name + ' Destination: ' + conn_details['dstIP'] + ':' + str(conn_details['dstPort']) + the_dns) 
Example #20
Source File: test_socket.py    From oss-ftp with 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 #21
Source File: network.py    From network_tech with Apache License 2.0 6 votes vote down vote up
def ptr_lookup(cls, network):
        ip = str(ipaddress.ip_interface(network).ip)
        try:
            primary_hostname, alias_hostnames, other_ips = socket.gethostbyaddr(ip)
        except socket.herror as e:
            logger.debug('DNS Reverse Lookup Error {}'.format(e))
            return Html.div('DNS: n/a')

        content = Html.div(
            'DNS: {}'.format(
                socket.getfqdn(primary_hostname)
            )
        )

        if alias_hostnames:
            content += Html.div('DNS Aliases:')
        for hostname in alias_hostnames:
            fqdn_hostname = socket.getfqdn(hostname)
            logger.debug('Alias {} FQDN {}'.format(hostname, fqdn_hostname))
            content += Html.div(fqdn_hostname)
        return content 
Example #22
Source File: helper.py    From FuzzFlow with 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 #23
Source File: RoHoneypot.py    From networking with GNU General Public License v3.0 5 votes vote down vote up
def deepscan2(target,chan):
	data = str(socket.gethostbyaddr(target))
	data = data.replace(",","").replace("[","").replace("]","").replace("(","").replace(")","").replace("'","")
	data = data.split()
	d1 = "-Name: "+data[0]
	d2 = "-FQDN: "+data[1]
	d3 = "-Provider: "+data[2]
	chan.send("   "+d1+"\r\n")
	chan.send("   "+d2+"\r\n")
	chan.send("   "+d3+"\r\n") 
Example #24
Source File: FunnyHoney.py    From networking with GNU General Public License v3.0 5 votes vote down vote up
def deepscan2(target,chan):
	data = str(socket.gethostbyaddr(target))
	data = data.replace(",","").replace("[","").replace("]","").replace("(","").replace(")","").replace("'","")
	data = data.split()
	d1 = "-Name: "+data[0]
	d2 = "-FQDN: "+data[1]
	d3 = "-Provider: "+data[2]
	chan.send("   "+d1+"\r\n")
	chan.send("   "+d2+"\r\n")
	chan.send("   "+d3+"\r\n") 
Example #25
Source File: FunnyHoney.py    From networking with GNU General Public License v3.0 5 votes vote down vote up
def deepscan(target,f=None):
	data = str(socket.gethostbyaddr(target))
	data = data.replace(",","").replace("[","").replace("]","").replace("(","").replace(")","").replace("'","")
	data = data.split()
	d1 = "-Name: "+data[0]
	d2 = "-FQDN: "+data[1]
	d3 = "-Provider: "+data[2]
	print d1
	print d2
	print d3
	print ""
	f.write("-"+target+"\n")
	f.write(d1+"\n")
	f.write(d2+"\n")
	f.write(d3+"\n\n") 
Example #26
Source File: fields.py    From smod-1 with GNU General Public License v2.0 5 votes vote down vote up
def resolve(self, x):
        if self in conf.resolve:
            try:
                ret = socket.gethostbyaddr(x)[0]
            except:
                pass
            else:
                if ret:
                    return ret
        return x 
Example #27
Source File: volreport.py    From mapr-ansible with Apache License 2.0 5 votes vote down vote up
def getHostname(replica):
    colonidx = replica.find(':')
    name, alias, addresslist = socket.gethostbyaddr(replica[:colonidx])
    return name 
Example #28
Source File: traceroute.py    From FinalRecon with MIT License 5 votes vote down vote up
def tcp_send(ip, port, ttl, rx, status, tr_tout, output, collect):
	tx = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	tx.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl))
	tx.setblocking(0)
	tx.settimeout(tr_tout)
	
	while True:
		try:
			try:
				tx.connect((ip, port))
				hop_index = str(ttl)
				try:
					hop_host = socket.gethostbyaddr(ip)[0]
				except socket.herror:
					hop_host = 'Unknown'
				print(G + hop_index.ljust(7) + C + ip.ljust(17) + W + hop_host)
				status['end'] = True
				if output != 'None':
					collect.setdefault('Result', []).append([str(hop_index), str(ip), str(hop_host)])
			except (socket.error, socket.timeout) as err:
				try:
					data, curr_addr = rx.recvfrom(512)
					curr_addr = curr_addr[0]
				except socket.timeout:
					curr_addr = '* * *'
				hop_index = str(ttl)
				hop_addr = curr_addr
				if hop_addr != '* * *':
					try:
						hop_host = socket.gethostbyaddr(hop_addr)[0]
					except socket.herror:
						hop_host = 'Unknown'
				else:
					hop_addr = '* * *'
					hop_host = ''
				print(G + hop_index.ljust(7) + C + hop_addr.ljust(17) + W + hop_host)
				if output != 'None':
					collect.setdefault('Result', []).append([str(hop_index), str(hop_addr), str(hop_host)])
				continue
		finally:
			tx.close()
			break 
Example #29
Source File: traceroute.py    From FinalRecon with MIT License 5 votes vote down vote up
def udp_send(ip, port, ttl, rx, status, tr_tout, output, collect):
	tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	tx.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
	tx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
	tx.setblocking(0)
	tx.settimeout(tr_tout)
	tx.sendto(''.encode(), (ip, port))

	try:
		data, curr_addr = rx.recvfrom(512)
		curr_addr = curr_addr[0]
	except socket.error as e:
		curr_addr = '* * *'
	finally:
		tx.close()
	
	hop_index = str(ttl)
	hop_addr = curr_addr
	if hop_addr != '* * *':
		try:
			hop_host = socket.gethostbyaddr(hop_addr)[0]
		except socket.herror:
			hop_host = 'Unknown'
	else:
		hop_addr = '* * *'
		hop_host = ''

	print(G + hop_index.ljust(7) + C + hop_addr.ljust(17) + W + hop_host)
	if output != 'None':
		collect.setdefault('Result', []).append([str(hop_index), str(hop_addr), str(hop_host)])

	if curr_addr == ip:
		status['end'] = True 
Example #30
Source File: hosthunter.py    From AttackSurfaceMapper with GNU General Public License v3.0 5 votes vote down vote up
def r_dns(targetIP):
    try:
        hostname = socket.gethostbyaddr(targetIP.address)
        if hostname[0] is not "":
            targetIP.hostname.append(hostname[0])
        # print("[Debug] r_dns result " + hostname[0]) ## Debug Statement
    except:
        pass


# query_api Function