Python socket.gethostbyaddr方法代码示例

本文整理汇总了Python中socket.gethostbyaddr方法的典型用法代码示例。如果您正苦于以下问题:Python socket.gethostbyaddr方法的具体用法?Python socket.gethostbyaddr怎么用?Python socket.gethostbyaddr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块socket的用法示例。

在下文中一共展示了socket.gethostbyaddr方法的24个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:klattimer,项目名称:LGWebOSRemote,代码行数:23,代码来源:auth.py


示例2: process

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:tatanus,项目名称:apt2,代码行数:21,代码来源:scan_gethostname.py


示例3: testHostnameRes

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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))) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:20,代码来源:test_socket.py


示例4: register_host

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:talos-vulndev,项目名称:FuzzFlow,代码行数:25,代码来源:helper.py


示例5: ip2name

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:Yukinoshita47,项目名称:Yuki-Chan-The-Auto-Pentest,代码行数:21,代码来源:common.py


示例6: ip_to_host

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:gluster,项目名称:gstatus,代码行数:19,代码来源:network.py


示例7: ip2hostname

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:ysrc,项目名称:xunfeng,代码行数:24,代码来源:scan.py


示例8: testHostnameRes

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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))) 
开发者ID:dxwu,项目名称:BinderFilter,代码行数:20,代码来源:test_socket.py


示例9: ptr_lookup

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:heyglen,项目名称:network_tech,代码行数:23,代码来源:network.py


示例10: whois

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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) 
开发者ID:rajeshmajumdar,项目名称:webdigger,代码行数:24,代码来源:__init__.py


示例11: addUTMPEntry

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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() 
开发者ID:proxysh,项目名称:Safejumper-for-Desktop,代码行数:27,代码来源:unix.py


示例12: get_local_hostname

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:20,代码来源:__init__.py


示例13: testHostnameRes

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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))) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:20,代码来源:test_socket.py


示例14: port_forward_log

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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) 
开发者ID:tnich,项目名称:honssh,代码行数:20,代码来源:output_handler.py


示例15: whois

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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) 
开发者ID:richardpenman,项目名称:whois,代码行数:24,代码来源:__init__.py


示例16: _get_reverse_dns

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:matamorphosis,项目名称:Scrummage,代码行数:25,代码来源:checkdmarc.py


示例17: override_system_resolver

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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 
开发者ID:elgatito,项目名称:script.elementum.burst,代码行数:26,代码来源:resolver.py


示例18: describe_cidr

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
def describe_cidr(cidr):
    import ipwhois, ipaddress, socket
    address = ipaddress.ip_network(str(cidr)).network_address
    try:
        whois = ipwhois.IPWhois(address).lookup_rdap()
        whois_names = [whois["asn_country_code"]] if "asn_country_code" in whois else []
        whois_names += [o.get("contact", {}).get("name", "") for o in whois.get("objects", {}).values()]
    except Exception:
        try:
            whois_names = [socket.gethostbyaddr(address)]
        except Exception:
            whois_names = [cidr]
    return ", ".join(str(n) for n in whois_names) 
开发者ID:kislyuk,项目名称:aegea,代码行数:15,代码来源:__init__.py


示例19: main

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--ifAddr', help='Send out on the interface with the given address.')
    args = parser.parse_args()
    msearch = 'M-SEARCH * HTTP/1.1\r\n' \
              'HOST:239.255.255.250:1900\r\n' \
              'ST:upnp:rootdevice\r\n' \
              'MX:2\r\n' \
              'MAN:"ssdp:discover"\r\n' \
              '\r\n'
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    if args.ifAddr:
        s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(args.ifAddr))
    s.settimeout(2)
    s.sendto(msearch.encode('utf-8'), ('239.255.255.250', 1900))
    try:
        while True:
            data, addr = s.recvfrom(65535)
            try:
                print('%s [%s]' % (socket.gethostbyaddr(addr[0])[0], addr[0]))
            except socket.herror:
                print(addr[0])
            print(data)
    except socket.timeout:
        pass 
开发者ID:alsmith,项目名称:multicast-relay,代码行数:31,代码来源:ssdpDiscover.py


示例20: resolve_hostname

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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.') 
开发者ID:remg427,项目名称:misp42splunk,代码行数:31,代码来源:net_utils.py


示例21: get_host_by_ip

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
def get_host_by_ip(value):
    try:
        ip = socket.gethostbyaddr(value)
        return ip
    except:
        return False 
开发者ID:AeonDave,项目名称:tilt,代码行数:8,代码来源:core.py


示例22: _normalize_url_with_hostname

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
def _normalize_url_with_hostname(url):
    # type: (Text) -> Text
    # TODO: replace urlparse by more robust utf-8 handling code
    parsed = urlparse(url.encode("utf-8"))
    hostname = parsed.hostname.decode("utf-8")  # type: ignore
    try:
        ipaddress.ip_address(hostname)
        hostname = socket.gethostbyaddr(hostname)[0].encode("utf-8")
    except ValueError:
        return url
    return parsed._replace(netloc=b"%s:%d" % (hostname, parsed.port)).geturl() 
开发者ID:prestosql,项目名称:presto-python-client,代码行数:13,代码来源:redirect.py


示例23: get_localhost_details

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
def get_localhost_details(interfaces_eth, interfaces_wlan):
    hostdata = "None"
    hostname = "None"
    windows_ip = "None"
    eth_ip = "None"
    wlan_ip = "None"
    host_fqdn = "None"
    eth_mac = "None"
    wlan_mac = "None"
    windows_mac = "None"
    hostname = socket.gethostbyname(socket.gethostname())
    if hostname.startswith("127.") and os.name != "nt":
        hostdata = socket.gethostbyaddr(socket.gethostname())
        hostname = str(hostdata[1]).strip('[]')
        host_fqdn = socket.getfqdn()
        for interface in interfaces_eth:
            try:
                eth_ip = get_ip(interface)
                if not "None" in eth_ip:
                    eth_mac = get_mac_address(interface)
                break
            except IOError:
                pass
        for interface in interfaces_wlan:
            try:
                wlan_ip = get_ip(interface)
                if not "None" in wlan_ip:
                    wlan_mac = get_mac_address(interface)
                break
            except IOError:
                pass
    else:
        windows_ip = socket.gethostbyname(socket.gethostname())
        windows_mac = uuid.getnode()
        windows_mac = ':'.join(("%012X" % windows_mac)[i:i+2] for i in range(0, 12, 2))
        hostdata = socket.gethostbyaddr(socket.gethostname())
        hostname = str(socket.gethostname())
        host_fqdn = socket.getfqdn()
    return hostdata, hostname, windows_ip, eth_ip, wlan_ip, host_fqdn, eth_mac, wlan_mac, windows_mac 
开发者ID:funkandwagnalls,项目名称:pythonpentest,代码行数:41,代码来源:hostdetails.py


示例24: run

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyaddr [as 别名]
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) 
开发者ID:micro-fan,项目名称:aiozk,代码行数:16,代码来源:diag.py



注:本文中的socket.gethostbyaddr方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。