Perform a forward lookup of a given hostname.

    Example:

    \b
    $ habu.dns.lookup.forward google.com
    {
        "ipv4": "172.217.168.46",
        "ipv6": "2a00:1450:400a:802::200e"
    }
501698
def cmd_dns_lookup_forward(hostname, verbose):
    
    if verbose:
        logging.basicConfig(level=logging.INFO, format='%(message)s')
        print("Looking up %s..." % hostname, file=sys.stderr)

    answer = lookup_forward(hostname)

    print(json.dumps(answer, indent=4))

    return True
425376
def ParseForwardedIps(self, forwarded_ips):
    
    addresses = []
    forwarded_ips = forwarded_ips or []
    for ip in forwarded_ips:
      if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)):
        addresses.append(ip[:-3] if ip.endswith('/32') else ip)
      else:
        self.logger.warning('Could not parse IP address: "%s".', ip)
    return addresses
979422
function getAddress (hostname) {
  if (net.isIP(hostname)) {
    return Promise.resolve(hostname);
  }
  return pify(dns.lookup)(hostname);
}
135931
public static String getIpByHost(String hostName) {
		try {
			return InetAddress.getByName(hostName).getHostAddress();
		} catch (UnknownHostException e) {
			return hostName;
		}
	}
107017
def _query_dns(self, host: str, family: int=socket.AF_INET) \
            -> dns.resolver.Answer:
        '''
        '''
        record_type = {socket.AF_INET: 'A', socket.AF_INET6: 'AAAA'}[family]

        event_loop = asyncio.get_event_loop()
        query = functools.partial(
            self._dns_resolver.query, host, record_type,
            source=self._bind_address)

        try:
            answer = yield from event_loop.run_in_executor(None, query)
        except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer) as error:
            # dnspython doesn't raise an instance with a message, so use the
            # class name instead.
            raise DNSNotFound(
                'DNS resolution failed: {error}'
                .format(error=wpull.util.get_exception_message(error))
            ) from error
        except dns.exception.DNSException as error:
            raise NetworkError(
                'DNS resolution error: {error}'
                .format(error=wpull.util.get_exception_message(error))
            ) from error
        else:
            return answer
1114644
function getFqdnForHostname(hostname, cb) {
  let addressIndex = 0;

  dns.lookup(hostname, { all: true }, function (err, addresses, family) {
    const tryNextAddressOrComplete = (err, fqdn) => {
      addressIndex++;
      if (!err) {
        cb(err, fqdn);
      } else if (addressIndex != addresses.length) {
        getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete);
      } else {
        cb(err);
      }
    };

    if (!err) {
      getFqdnForIpAddress(addresses[addressIndex].address, tryNextAddressOrComplete);
    } else {
      cb(err);
    }
  });
}
431650
def eff_request_host(request):
    
    erhn = req_host = request_host(request)
    if req_host.find(".") == -1 and not IPV4_RE.search(req_host):
        erhn = req_host + ".local"
    return req_host, erhn
1196230
def get_forwarders(resolv="resolv.conf"):
    
    ns = []
    if os.path.exists(resolv):
        for l in open(resolv):
            if l.startswith("nameserver"):
                address = l.strip().split(" ", 2)[1]
                # forwarding to ourselves would be bad
                if not address.startswith("127"):
                    ns.append(address)
    if not ns:
        ns = ['8.8.8.8', '8.8.4.4']
    return ns
1321109
def target_to_hostname(target):
    

    if len(target) == 0 or len(target) > 255:
        return None
    if not re.match(r'^[\w.-]+$', target):
        return None
    return [target]
162828
@Override
    public Host lookup( final String hostName )
    {
        boolean isNew = false;
        Host h = hosts.get( hostName );
        if ( h == null )
        {
            isNew = true;
            h = new Host();
        }

        if ( h.isPatternsApplied() )
        {
            return h;
        }

        if ( h.getHostName() == null )
        {
            h.setHostName( hostName );
        }

        if ( h.getUser() == null )
        {
            h.setUser( userName() );
        }

        if ( h.getPort() < 1 )
        {
            h.setPort( SSH_PORT );
        }

        h.setPatternsApplied( true );

        if ( isNew )
        {
            hosts.put( hostName, h );
        }

        return h;
    }
202597
def determine_hostname(display_name=None):
    
    if display_name:
        # if display_name is provided, just return the given name
        return display_name
    else:
        socket_gethostname = socket.gethostname()
        socket_fqdn = socket.getfqdn()

        try:
            socket_ex = socket.gethostbyname_ex(socket_gethostname)[0]
        except (LookupError, socket.gaierror):
            socket_ex = ''

        gethostname_len = len(socket_gethostname)
        fqdn_len = len(socket_fqdn)
        ex_len = len(socket_ex)

        if fqdn_len > gethostname_len or ex_len > gethostname_len:
            if "localhost" not in socket_ex and len(socket_ex):
                return socket_ex
            if "localhost" not in socket_fqdn:
                return socket_fqdn

        return socket_gethostname
100826
def search_hosts(self, ip):
        
        c = CensysIPv4(api_id=self.__uid, api_secret=self.__api_key)
        return c.view(ip)
38100
def parse_ipv6_hostname(cls, hostname):
        ''''''
        if not hostname.startswith('[') or not hostname.endswith(']'):
            raise ValueError('Invalid IPv6 address: {}'
                             .format(ascii(hostname)))

        hostname = ipaddress.IPv6Address(hostname[1:-1]).compressed

        return hostname
136152
def get_hostname(url):
        

        if url not in URLHelper.__cache:
            URLHelper.__cache[url] = urlparse(url)

        parts = URLHelper.__cache[url].netloc.split(".")

        if len(parts) == 1:
            return parts[0]
        else:
            return ".".join(parts[-2:-1])
1266851
def host2id(self, hostname):
        """"""
        for key, value in self.server_map.items():
            if value == hostname:
                return key
1245943
def _ipaddress_match(ipname, host_ip):
    
    # OpenSSL may add a trailing newline to a subjectAltName's IP address
    # Divergence from upstream: ipaddress can't handle byte str
    ip = ipaddress.ip_address(_to_unicode(ipname).rstrip())
    return ip == host_ip
74725
def valid_hostname(host):
    
    if len(host) > 255:
        return False

    if host[-1:] == '.':
        host = host[:-1]

    return all(_hostname_re.match(c) for c in host.split('.'))