Python socket.gethostbyname_ex() Examples

The following are 30 code examples of socket.gethostbyname_ex(). 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: ip.py    From pynmap with GNU General Public License v3.0 8 votes vote down vote up
def getLocalip(interface: str = "wlan0") -> str:
    """This function will return the Local IP Address of the interface"""
    if "nux" in sys.platform:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            return socket.inet_ntoa(
                fcntl.ioctl(
                    s.fileno(), 0x8915, struct.pack('256s',interface[:15])
                )[20:24]
            )
        except IOError:
            print("{}[!] Error, unable to detect local ip address.".format(Colors.FAIL))
            print("[!] Check your connection to network {}".format(Colors.ENDC))
            exit()
    elif "darwin" in sys.platform:
        return [ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][0] 
Example #2
Source File: bounces_steps.py    From paasta with Apache License 2.0 6 votes vote down vote up
def should_be_discoverable_on_port(context, host_port):
    all_discovered = {}
    for slave_ip in socket.gethostbyname_ex("mesosslave")[2]:
        with mock.patch(
            "paasta_tools.mesos_tools.socket.getfqdn",
            return_value=slave_ip,
            autospec=True,
        ):
            discovered = marathon_tools.marathon_services_running_here()
            all_discovered[slave_ip] = discovered
            if discovered == [("bounce", "test1", host_port)]:
                return

    raise Exception(
        "Did not find bounce.test1 in marathon_services_running_here for any of our slaves: %r",
        all_discovered,
    ) 
Example #3
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 #4
Source File: utils.py    From bigquery-bokeh-dashboard with Apache License 2.0 6 votes vote down vote up
def _resync(self):
        """
        Check if the list of available nodes has changed. If any change is
        detected, a new HashClient pointing to all currently available
        nodes is returned, otherwise the current client is returned.
        """
        # Collect the all Memcached pods' IP addresses
        try:
            _, _, ips = socket.gethostbyname_ex(self.host)
        except socket.gaierror:
            # The host could not be found. This mean that either the service is
            # down or that no pods are running
            ips = []
        if set(ips) != set(self._ips):
            # A different list of ips has been detected, so we generate
            # a new client
            self._ips = ips
            if self._ips:
                servers = [(ip, self.port) for ip in self._ips]
                self._client = HashClient(servers, use_pooling=True)
            else:
                self._client = None 
Example #5
Source File: fsurfing.py    From f-surfing with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_ip_address():
    if platform.system() == "Windows":
        import socket
        ipList = socket.gethostbyname_ex(socket.gethostname())
        j = 0
        print "Index | IP"
        for i in ipList[2]:
            print j, "     ",i
            j = j + 1
        index = int(raw_input("Please input the index number of you IP address.(Usually, the IP looks like 10.xxx.xxx.xxx):\n"))
        if index >= 0 and index < len(ipList[2]):
            return ipList[2][index]
        else:
            print "Invalid Index number"
            exit()
    ip=os.popen(". /lib/functions/network.sh; network_get_ipaddr ip wan; echo $ip").read()
    ip2=str(ip).split("\n")[0]
    return ip2 
Example #6
Source File: subdomain.py    From w9scan with GNU General Public License v2.0 6 votes vote down vote up
def audit(arg):
    domain = util.get_domain_root(arg)
    
    tlds = util.list_from_file("database/sub_domain.txt")

    unable_pro = "sbsbsbsbforw9scanunablepro"
    hostnames = unable_pro + "." + domain
    hostnames = hostnames.strip()
    try:
        l = socket.gethostbyname_ex(hostnames)
    except socket.error:
        l = 0
    if l != 0:
        security_info("域名存在泛解析 %s" % ("*." + domain), 'subdomain')
        return

    for pro in tlds:
        hostnames = pro + "." + domain
        hostnames = hostnames.strip()
        try:
            l = socket.gethostbyname_ex(hostnames)
            security_info(str(l),'subdomain')
            time.sleep(0.01)
        except socket.error:
            pass 
Example #7
Source File: socks.py    From OpenDoor with GNU General Public License v3.0 6 votes vote down vote up
def get_ips_addresses(host):
        """
        Get remote ip addresses
        :param str host: target host
        :return: list
        """

        try:
            _, _, ips_list = socket.gethostbyname_ex(host)
            if not ips_list:
                ips = ''
            else:
                ips = '['+', '.join(ips_list) +']'
        except socket.gaierror:
            ips = ''
        return ips 
Example #8
Source File: gpfs.py    From manila with Apache License 2.0 6 votes vote down vote up
def _publish_access(self, *cmd, **kwargs):
        check_exit_code = kwargs.get('check_exit_code', True)

        outs = []
        localserver_iplist = socket.gethostbyname_ex(socket.gethostname())[2]
        for server in self.configuration.gpfs_nfs_server_list:
            if server in localserver_iplist:
                run_command = cmd
                run_local = True
            else:
                sshlogin = self.configuration.gpfs_ssh_login
                remote_login = sshlogin + '@' + server
                run_command = ['ssh', remote_login] + list(cmd)
                run_local = False
            try:
                out = utils.execute(*run_command,
                                    run_as_root=run_local,
                                    check_exit_code=check_exit_code)
            except exception.ProcessExecutionError:
                raise
            outs.append(out)
        return outs 
Example #9
Source File: kube_master.py    From wardroom with Apache License 2.0 6 votes vote down vote up
def kube_lookup_hostname(self, ip, hostname, many=False):
        ips = set()

        ip = ip.split(':')[0]
        if ip and ip != "":
            if re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", ip):
                ips.add(ip)
        try:
            (_, _, iplist) = socket.gethostbyname_ex(hostname)
            ips |= set(iplist)
        except socket.error as e:
            pass

        if many:
            ips.add(hostname)
            return sorted(list(ips))
        else:
            return sorted(list(ips))[0] 
Example #10
Source File: factory.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def discover(service_name, host = None, registrar = None, timeout = 2):
    """
    discovers hosts running the given service
    
    :param service_name: the service to look for
    :param host: limit the discovery to the given host only (None means any host)
    :param registrar: use this registry client to discover services. if None,
                      use the default UDPRegistryClient with the default settings.
    :param timeout: the number of seconds to wait for a reply from the registry
                    if no hosts are found, raises DiscoveryError
    
    :raises: ``DiscoveryError`` if no server is found
    :returns: a list of (ip, port) pairs
    """
    if registrar is None:
        registrar = UDPRegistryClient(timeout = timeout)
    addrs = registrar.discover(service_name)
    if not addrs:
        raise DiscoveryError("no servers exposing %r were found" % (service_name,))
    if host:
        ips = socket.gethostbyname_ex(host)[2]
        addrs = [(h, p) for h, p in addrs if h in ips]
    if not addrs:
        raise DiscoveryError("no servers exposing %r were found on %r" % (service_name, host))
    return addrs 
Example #11
Source File: factory.py    From NoobSec-Toolkit with GNU General Public License v2.0 6 votes vote down vote up
def discover(service_name, host = None, registrar = None, timeout = 2):
    """
    discovers hosts running the given service
    
    :param service_name: the service to look for
    :param host: limit the discovery to the given host only (None means any host)
    :param registrar: use this registry client to discover services. if None,
                      use the default UDPRegistryClient with the default settings.
    :param timeout: the number of seconds to wait for a reply from the registry
                    if no hosts are found, raises DiscoveryError
    
    :raises: ``DiscoveryError`` if no server is found
    :returns: a list of (ip, port) pairs
    """
    if registrar is None:
        registrar = UDPRegistryClient(timeout = timeout)
    addrs = registrar.discover(service_name)
    if not addrs:
        raise DiscoveryError("no servers exposing %r were found" % (service_name,))
    if host:
        ips = socket.gethostbyname_ex(host)[2]
        addrs = [(h, p) for h, p in addrs if h in ips]
    if not addrs:
        raise DiscoveryError("no servers exposing %r were found on %r" % (service_name, host))
    return addrs 
Example #12
Source File: wechat-sendall.py    From wechat-sendall with Apache License 2.0 6 votes vote down vote up
def getQRImage():
  path = os.path.join(os.getcwd(), "qrcode.jpg")
  url = "https://login.weixin.qq.com/qrcode/" + uuid
  r = s.get(url, stream=True)
  # debugReq(r)
  if r.status_code == 200:
    with open(path, 'wb') as f:
      r.raw.decode_content = True
      shutil.copyfileobj(r.raw, f)
  import socket
  ip = [l
        for l in
        ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2]
          if not ip.startswith("127.")][:1],
         [[(sc.connect(('8.8.8.8', 80)), sc.getsockname()[0], sc.close())
           for sc in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]])
        if l][0][0]
  print "[+] Please open http://" + ip + ":" + str(http_port) + "/qrcode.jpg or open " + path

  time.sleep(1) 
Example #13
Source File: LaunchManyCore.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def guess_ext_ip_from_local_info(self):
        try:
            ip = get_my_wan_ip()
            if DEBUG:
                log('lm::guess_ext_ip_from_local_info: result of get_my_wan_ip()', ip)
            if ip is None:
                host = socket.gethostbyname_ex(socket.gethostname())
                if DEBUG:
                    log('lm::guess_ext_ip_from_local_info: try to find ip from host: hostname', socket.gethostname(), 'result', host)
                ipaddrlist = host[2]
                for ip in ipaddrlist:
                    return ip

                return '127.0.0.1'
            return ip
        except:
            return '127.0.0.1' 
Example #14
Source File: cloudfrunt.py    From cloudfrunt with MIT License 6 votes vote down vote up
def get_cf_domain(domain,cf_ranges):

    if domain.endswith('cloudfront.net'):
        return False

    domain_ips = []

    try:
        domain_ips = socket.gethostbyname_ex(domain)[2]
    except:
        pass

    for ip in domain_ips:
        for ip_range in cf_ranges:
            ip_network = IPNetwork(ip_range)
            if ip in ip_network:
                print(' [+] Found CloudFront domain --> ' + str(domain))
                return True
    return False

# test domains for CloudFront misconfigurations 
Example #15
Source File: utils.py    From paasta with Apache License 2.0 6 votes vote down vote up
def calculate_remote_masters(
    cluster: str, system_paasta_config: SystemPaastaConfig
) -> Tuple[List[str], str]:
    """Given a cluster, do a DNS lookup of that cluster (which
    happens to point, eventually, to the Mesos masters in that cluster).
    Return IPs of those Mesos masters.
    """

    cluster_fqdn = system_paasta_config.get_cluster_fqdn_format().format(
        cluster=cluster
    )
    try:
        _, _, ips = socket.gethostbyname_ex(cluster_fqdn)
        output = None
    except socket.gaierror as e:
        output = f"ERROR while doing DNS lookup of {cluster_fqdn}:\n{e.strerror}\n "
        ips = []
    return (ips, output) 
Example #16
Source File: request.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def thishost():
    """Return the IP addresses of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
        except socket.gaierror:
            _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
    return _thishost 
Example #17
Source File: info.py    From Loki with MIT License 5 votes vote down vote up
def get_internal_ip(self):
        try:
            return socket.gethostbyname_ex(socket.gethostname())[-1][-1]
        except:
            return '' 
Example #18
Source File: zdd.py    From marathon-lb with Apache License 2.0 5 votes vote down vote up
def _get_alias_records(hostname):
    """Return all IPv4 A records for a given hostname
    """
    return socket.gethostbyname_ex(hostname)[2] 
Example #19
Source File: bluegreen_deploy.py    From marathon-lb with Apache License 2.0 5 votes vote down vote up
def _get_alias_records(hostname):
    """Return all IPv4 A records for a given hostname
    """
    return socket.gethostbyname_ex(hostname)[2] 
Example #20
Source File: request.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def thishost():
    """Return the IP addresses of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
        except socket.gaierror:
            _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
    return _thishost 
Example #21
Source File: request.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
Example #22
Source File: net.py    From dagster with Apache License 2.0 5 votes vote down vote up
def is_local_uri(address):
    '''Determine if an address (full URI, DNS or IP) is local.

    Args:
        address (str): The URI or IP address to evaluate

    Returns:
        bool: Whether the address appears to represent a local interface.
    '''
    check.str_param(address, 'address')

    # Handle the simple cases with no protocol specified. Per
    # https://docs.python.org/3/library/urllib.parse.html, urlparse recognizes a netloc only if it
    # is properly introduced by '//' (e.g. has a scheme specified).
    hostname = urlparse(address).hostname if '//' in address else address.split(':')[0]

    # Empty protocol only specified as URI, e.g. "rpc://"
    if hostname is None:
        return True

    # Get the IPv4 address from the hostname. Returns a triple (hostname, aliaslist, ipaddrlist), so
    # we grab the 0th element of ipaddrlist.
    try:
        ip_addr_str = socket.gethostbyname_ex(hostname)[-1][0]
    except socket.gaierror:
        # Invalid hostname, so assume not local host
        return False

    # Special case this since it isn't technically loopback
    if ip_addr_str == '0.0.0.0':
        return True

    return is_loopback(ip_addr_str) 
Example #23
Source File: resolver.py    From script.elementum.burst with Do What The F*ck You Want To Public License 5 votes vote down vote up
def restore_system_resolver():
    """Undo the effects of override_system_resolver().
    """
    global _resolver
    _resolver = None
    socket.getaddrinfo = _original_getaddrinfo
    socket.getnameinfo = _original_getnameinfo
    socket.getfqdn = _original_getfqdn
    socket.gethostbyname = _original_gethostbyname
    socket.gethostbyname_ex = _original_gethostbyname_ex
    socket.gethostbyaddr = _original_gethostbyaddr 
Example #24
Source File: request.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def thishost():
    """Return the IP addresses of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
        except socket.gaierror:
            _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
    return _thishost 
Example #25
Source File: portForward.py    From honssh with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, out, uuid, chan_name, ssh, conn_details, parent, otherParent):
        super(PortForward, self).__init__(uuid, chan_name, ssh)

        self.out = out
        self.out.register_self(self)
        self.baseParent = parent
        self.otherBaseParent = otherParent

        self.connDetails = conn_details
        self.connDetails['dstIP'] = socket.gethostbyname_ex(self.connDetails['dstIP'])[2][0]
        self.connDetails['srcIP'] = socket.gethostbyname_ex(self.connDetails['srcIP'])[2][0]

        self.out.port_forward_log(self.name, self.connDetails)

        self.pcapFile = self.out.logLocation + datetime.datetime.now().strftime("%Y%m%d_%H%M%S_%f") + '_' \
                        + self.name[1:-1] + '.pcap'
        self.write_to_pcap(self.pcapGlobalHeader)
        self.doAcksNow = False
        self.tcpFlags = ''

        self.serverSeq = 1
        self.clientSeq = 0
        self.do_tcp_handshake()

        self.parent = None
        self.payload = None 
Example #26
Source File: request.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
Example #27
Source File: request.py    From Imogen with MIT License 5 votes vote down vote up
def thishost():
    """Return the IP addresses of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = tuple(socket.gethostbyname_ex(socket.gethostname())[2])
        except socket.gaierror:
            _thishost = tuple(socket.gethostbyname_ex('localhost')[2])
    return _thishost 
Example #28
Source File: domainip.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def c():
    """Get ipaddress of domain..GO DNS!"""
    domain = raw_input("Domain: ")
    #try to resolve.
    try:
        chk = socket.gethostbyname_ex(domain)
    except Exception:
        print "[+]ERROR: could not get hostname!"
        raise
    print "\nIP Address of", domain, ":", chk[2], "\n"
    return 
Example #29
Source File: request.py    From Imogen with MIT License 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
Example #30
Source File: domainip.py    From NoobSec-Toolkit with GNU General Public License v2.0 5 votes vote down vote up
def c():
    """Get ipaddress of domain..GO DNS!"""
    domain = raw_input("Domain: ")
    #try to resolve.
    try:
        chk = socket.gethostbyname_ex(domain)
    except Exception:
        print "[+]ERROR: could not get hostname!"
        raise
    print "\nIP Address of", domain, ":", chk[2], "\n"
    return