我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.gethostbyaddr()。
def discover(data: ConnectionData) -> None: assert isinstance(data, ConnectionData) ip_net, iface = data try: ans, unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip_net), iface=iface, timeout=2, verbose=False) for s, r in ans: line = r.sprintf("%Ether.src% %ARP.psrc%") try: hostname = socket.gethostbyaddr(r.psrc) line += ' ' + hostname[0] except socket.herror: pass print(line) except PermissionError: print('Cannot execute necessary code, did you run as root?') sys.exit(1) except: raise
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 str: address = self._searchHostAddr(address) if (type(address) == tuple): (host, port) = address[:2] try: host = socket.gethostbyname(host) except socket.error: pass address = (host, port) if (address in list(self.targets.keys())): try: (host, _, _) = socket.gethostbyaddr(host) except socket.error: pass return ((host, port), self.targets[address]) return (None, ['',{}])
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()
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
def resolveIP(self, ipaddr): ret = list() self.sf.debug("Performing reverse-resolve of " + ipaddr) if ipaddr in self.resolveCache: self.sf.debug("Returning cached result for " + ipaddr + " (" + str(self.resolveCache[ipaddr]) + ")") return self.resolveCache[ipaddr] try: addrs = self.sf.normalizeDNS(socket.gethostbyaddr(ipaddr)) self.resolveCache[ipaddr] = addrs self.sf.debug("Resolved " + ipaddr + " to: " + str(addrs)) return addrs except BaseException as e: self.sf.debug("Unable to resolve " + ipaddr + " (" + str(e) + ")") self.resolveCache[ipaddr] = list() return ret # Resolve a host
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
def get_name_from_ip(self, addr): # pylint: disable=no-self-use """Returns a reverse dns name if available. :param addr: IP Address :type addr: ~.common.Addr :returns: name or empty string if name cannot be determined :rtype: str """ # If it isn't a private IP, do a reverse DNS lookup if not common.private_ips_regex.match(addr.get_addr()): try: socket.inet_aton(addr.get_addr()) return socket.gethostbyaddr(addr.get_addr())[0] except (socket.error, socket.herror, socket.timeout): pass return ""
def run(self): #do pings for x in range(0, self.repeat): self.one_ping(self.ip, self.port, self.identifier, self.sequence, self.ttl, self.timeout) self.sequence += 1 if x != self.repeat -1: time.sleep(self.sleep) #count packet loss self.result['packet_loss'] /= self.repeat #try to get hostname try: self.result['hostname'] = socket.gethostbyaddr(self.ip)[0] except socket.herror: self.result['hostname'] = None #calculate averate time if len(self.result['times']) != 0: self.result['avg_time'] = sum(self.result['times']) / len(self.result['times']) #and calculate mdev mean = sum([float(x) for x in self.result['times']]) / len(self.result['times']) self.result['mdev'] = sum([abs(x - mean) for x in self.result['times']]) / len(self.result['times']) return self.result
def scan_and_print_neighbors(net, interface, timeout=1): global ips_o print_fmt("\n\033[94m[ARP]\033[0m %s sur %s" % (net, interface)) try: ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=False) for s, r in ans.res: line = r.sprintf("%Ether.src% %ARP.psrc%") ips_o.append(line.split(' ')[2]) line = mac_address_id(line) try: hostname = socket.gethostbyaddr(r.psrc) line += " " + hostname[0] except socket.herror: pass except KeyboardInterrupt: print '\033[91m[-]\033[0m L\'utilisateur a choisi l\'interruption du process.' break logger.info("\033[96m[ONLINE]\033[0m " + line) except socket.error as e: if e.errno == errno.EPERM: logger.error("\033[91m[-]\033[0m %s. Vous n'etes pas root?", e.strerror) else: raise
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)
def validate_hostname(hostname): """ Validates that the Foreman API uses a FQDN as hostname. Also looks up the "real" hostname if "localhost" is specified. Otherwise, the picky Foreman API won't connect. :param hostname: the hostname to validate :type hostname: str """ if hostname == "localhost": #get real hostname hostname = socket.gethostname() else: #convert to FQDN if possible: fqdn = socket.gethostbyaddr(hostname) if "." in fqdn[0]: hostname = fqdn[0] return hostname
def _hostname_linux(self): """ Returns system hostname. """ # Default value found using platform hostname = platform.node() try: # Try to get hostname (FQDN) using 'hostname -f' (rc, out, err) = exec_command([which('hostname'), '-f']) if rc == 0: hostname = out.encode('utf-8').strip() except Exception: try: # Try to get hostname (FQDN) using socket module (hostname, _, _) = socket.gethostbyaddr(socket.gethostname()) hostname = hostname.strip() except Exception: pass return hostname
def _check_address(address): ipv4 = "" hostname = "" if is_valid_address(address): ipv4 = address try: hostname = socket.gethostbyaddr(address)[0] except Exception: pass # no DNS else: hostname = socket.getfqdn(address) try: ipv4 = socket.gethostbyname(hostname) except Exception: pass # host not valid or offline return ipv4, hostname
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)))
def ip2hostname(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.sendto(query_data, (ip, dport)) x = _s.recvfrom(1024) tmp = x[0][57:] hostname = tmp.split("\x00", 2)[0].strip() hostname = hostname.split()[0] return hostname except: pass
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:] hostname = tmp.split("\x00", 2)[0].strip() hostname = hostname.split()[0] return hostname except: pass
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)))
def dnslookup(self, str): """ Perform DNS lookup on str. If first character of digit is numeric, assume that str contains an IP address. Otherwise, assume that str contains a hostname.""" if str == '': str = ' ' if str[0] in string.digits: try: value = socket.gethostbyaddr(str)[0] except: value = 'Lookup failed' else: try: value = socket.gethostbyname(str) except: value = 'Lookup failed' return value
def dnslookup(str): """ Perform DNS lookup on str. If first character of digit is numeric, assume that str contains an IP address. Otherwise, assume that str contains a hostname.""" if str == '': str = ' ' if str[0] in string.digits: try: value = socket.gethostbyaddr(str)[0] except: value = 'Lookup failed' else: try: value = socket.gethostbyname(str) except: value = 'Lookup failed' return value
def traceIP(target): try: base = GeoIP('GeoLiteCity.dat') data = base.record_by_addr(target) dnsName = socket.gethostbyaddr(target)[0] formatedData = '''IP: {} City: {} State/Province: {} Country: {} Continent: {} Zip/Postal code: {} Timezone: {} Latitude: {} Longitude: {} DNS name: {}'''.format(target, data['city'], data['region_code'], data['country_name'], data['continent'], data['postal_code'], data['time_zone'], str(data['latitude']), str(data['longitude']), dnsName) print formatedData # compares target to database and print results to console askSave = raw_input('Save data? Y/n: ').lower() if askSave == 'y': ipFileName = raw_input('Filename: ') with open(ipFileName, 'w') as fileName: fileName.write(formatedData) print 'Output saved as {}'.format(ipFileName) else: pass # asks user if they want to save the output pause() main() except socket.herror: pass
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.sendto(query_data, (ip, dport)) x = _s.recvfrom(1024) tmp = x[0][57:] hostname = tmp.split("\x00", 2)[0].strip() hostname = hostname.split()[0] return hostname except: pass
def TCP_connect(ip, port_number, delay, hosts): host_name = 'Unknown' TCPsock = socket.socket() TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) TCPsock.settimeout(delay) try: host_name = socket.gethostbyaddr(ip)[0] # print(host_name) except socket.herror: pass try: TCPsock.connect((ip, port_number)) if 'SSH' in str(TCPsock.recv(256)): hosts.append((host_name, ip)) # print(host_name,ip) except (OSError, ConnectionRefusedError): pass
def is_aws(ipaddr): if Validation.check_internet_connection(): if ipaddr in Validation.__aws_cache: return True elif ipaddr in Validation.__no_aws_cache: return False else: # if ipaddr not in chache try: result = socket.gethostbyaddr(ipaddr) for line in result: if 'compute.amazonaws.com' in line: Validation.__aws_cache.append(ipaddr) return True except socket.herror: Validation.__no_aws_cache.append(ipaddr) return False
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
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
def existing_mons(parameters): mons = json.loads( NS._int.client.read( "clusters/%s/maps/mon_map/data" % parameters["TendrlContext.integration_id"] ).value )['mons'] created_mons = [] for mon in mons: mon_ip = mon['addr'].split(':')[0] mon_host_name = socket.gethostbyaddr(mon_ip)[0] created_mons.append( { "address": mon_ip, "host": mon_host_name } ) return created_mons
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)))
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
def on_connect(self, caller): """Add account and player to caller.connection.""" con = caller.connection try: con.host = gethostbyaddr(con.host)[0] con.logger.name = '%s:%d' % (con.host, con.port) except Exception as e: con.logger.warning('Could not resolve the hostname:') con.logger.exception(e) con.connected_at = datetime.utcnow() con.account = None con.player = None con.notify(self.options.welcome_msg) reactor.callLater( self.options.login_timeout, do_timeout, con )
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, ['',{}])
def _generate_host(self, ip): host = None # Use UDP. socket.SOCK_DGRAM s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2.0) try: host_name, alias, ipaddr = socket.gethostbyaddr(str(ip)) host = Node.Node(ip, host_name) except socket.herror as ex: pass return host # Properties
def lookup_ip_address(self, ip): """ Perform a reverse DNS lookup for ip. Uses self.cache to speed up results when the same ip is lookup up several times during one session. :param ip: IP address to look up """ if ip is None: return None if ip not in self.cache: try: self.cache[ip] = gethostbyaddr(ip)[0] except (herror, gaierror): # if lookup fails, return the input address self.cache[ip] = ip return self.cache[ip]
def hostname(ip): """ Performs a DNS reverse lookup for an IP address and caches the result in a global variable, which is really, really stupid. :param ip: And IP address string. :returns: A hostname string or a False value if the lookup failed. """ addr = unicode(ip) if addr in _cached_hostname: return _cached_hostname[addr] try: dns = gethostbyaddr(addr) except herror: return False _cached_hostname[addr] = dns[0] return dns[0]
def resolve_ip_and_sysname(name): """Given a name that can be either an ip or a hostname/domain name, this function looks up IP and hostname. name - ip or hostname Returns: - tuple with ip-addres and sysname """ try: ip_addr = IP(name) except ValueError: ip_addr = IP(gethostbyname(name)) try: sysname = gethostbyaddr(unicode(ip_addr))[0] except SocketError: sysname = unicode(ip_addr) return (ip_addr, sysname)