我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.gethostbyname()。
def get_host_ip(hostname, fallback=None): """ Resolves the IP for a given hostname, or returns the input if it is already an IP. """ if is_ip(hostname): return hostname ip_addr = ns_query(hostname) if not ip_addr: try: ip_addr = socket.gethostbyname(hostname) except: log("Failed to resolve hostname '%s'" % (hostname), level=WARNING) return fallback return ip_addr
def setOSCTarget(self, address, prefix=None, filters=None): """Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget. the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port or a 'host' (string) : The host will be looked-up - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage sent to this OSCTarget (optional) """ if type(address) in str: address = self._searchHostAddr(address) elif (type(address) == tuple): (host, port) = address[:2] try: host = socket.gethostbyname(host) except: pass address = (host, port) else: raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string") self._setTarget(address, prefix, filters)
def delOSCTarget(self, address, prefix=None): """Delete the specified OSCTarget from the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the Target is only deleted if the address and prefix match. """ 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) self._delTarget(address, prefix)
def hasOSCTarget(self, address, prefix=None): """Return True if the given OSCTarget exists in the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the return-value is only True if the address and prefix match. """ 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()): if prefix == None: return True elif prefix == self.targets[address][0]: return True return False
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 setOSCTarget(self, address, prefix=None, filters=None): """Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget. the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port or a 'host' (string) : The host will be looked-up - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage sent to this OSCTarget (optional) """ if type(address) in types.StringTypes: address = self._searchHostAddr(address) elif (type(address) == types.TupleType): (host, port) = address[:2] try: host = socket.gethostbyname(host) except: pass address = (host, port) else: raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string") self._setTarget(address, prefix, filters)
def delOSCTarget(self, address, prefix=None): """Delete the specified OSCTarget from the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the Target is only deleted if the address and prefix match. """ 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) self._delTarget(address, prefix)
def hasOSCTarget(self, address, prefix=None): """Return True if the given OSCTarget exists in the Client's dict. the 'address' argument can be a ((host, port) tuple), or a hostname. If the 'prefix' argument is given, the return-value is only True if the address and prefix match. """ 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(): if prefix == None: return True elif prefix == self.targets[address][0]: return True return False
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 is_same_host(self, url): """ Check if the given ``url`` is a member of the same host as this connection pool. """ if url.startswith('/'): return True # TODO: Add optional support for socket.gethostbyname checking. scheme, host, port = get_host(url) # Use explicit default port for comparison when none is given if self.port and not port: port = port_by_scheme.get(scheme) elif not self.port and port == port_by_scheme.get(scheme): port = None return (scheme, host, port) == (self.scheme, self.host, self.port)
def output(data, udp): """ output the sensor backlog data, in JSON format always output to stdout output to udp if so specified """ print data if udp is None: return try: sockaddr_components = udp.split(':') ip = socket.gethostbyname(sockaddr_components[0]) port = int(sockaddr_components[1]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(data + '\n', (ip, port)) except Exception, e: print e return
def is_same_host(self, url): """ Check if the given ``url`` is a member of the same host as this connection pool. """ if url.startswith('/'): return True # TODO: Add optional support for socket.gethostbyname checking. scheme, host, port = get_host(url) host = _ipv6_host(host).lower() # Use explicit default port for comparison when none is given if self.port and not port: port = port_by_scheme.get(scheme) elif not self.port and port == port_by_scheme.get(scheme): port = None return (scheme, host, port) == (self.scheme, self.host, self.port)
def getStreamDef( self, name=None, hostip=None, pkts=1000, block=True, returnSddsAnalyzer=True): # grab data if stream definition is available sdef =None aid=name if not aid: if len(self._streamdefs) == 0: raise Exception("No attachment have been made, use grabData or call attach") aid = self._streamdefs.keys()[0] print "Defaults to first entry, attach id = ", aid sdef = self._streamdefs[aid] else: sdef = sefl._streamdefs[aid] if not sdef: raise Exception("No SDDS stream definition for attach id:" + aid ) if not hostip: hostip = _socket.gethostbyname(_socket.gethostname()) return self.getData( sdef.multicastAddress, hostip, sdef.port, packets, block=block, returnSDDSAnalyzer=returnSDDSAnalyzer)
def get_host_ip(hostname, fallback=None): """ Resolves the IP for a given hostname, or returns the input if it is already an IP. """ if is_ip(hostname): return hostname ip_addr = ns_query(hostname) if not ip_addr: try: ip_addr = socket.gethostbyname(hostname) except Exception: log("Failed to resolve hostname '%s'" % (hostname), level=WARNING) return fallback return ip_addr
def choose_boundary(): global _prefix if _prefix is None: hostid = socket.gethostbyname(socket.gethostname()) try: uid = `os.getuid()` except: uid = '1' try: pid = `os.getpid()` except: pid = '1' _prefix = hostid + '.' + uid + '.' + pid timestamp = '%.3f' % time.time() seed = `random.randint(0, 32767)` return _prefix + '.' + timestamp + '.' + seed
def choose_boundary(): """Return a string usable as a multipart boundary. The string chosen is unique within a single program run, and incorporates the user id (if available), process id (if available), and current time. So it's very unlikely the returned string appears in message text, but there's no guarantee. The boundary contains dots so you have to quote it in the header.""" global _prefix import time if _prefix is None: import socket try: hostid = socket.gethostbyname(socket.gethostname()) except socket.gaierror: hostid = '127.0.0.1' try: uid = repr(os.getuid()) except AttributeError: uid = '1' try: pid = repr(os.getpid()) except AttributeError: pid = '1' _prefix = hostid + '.' + uid + '.' + pid return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter()) # Subroutines for decoding some common content-transfer-types
def attack(): ip = socket.gethostbyname( host ) global n msg=str(string.letters+string.digits+string.punctuation) data="".join(random.sample(msg,5)) dos = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: n+=1 dos.connect((ip, port)) dos.send( "GET /%s HTTP/1.1\r\n" % data ) print "\n "+time.ctime().split(" ")[3]+" "+"["+str(n)+"] #-#-# Hold Your Tears #-#-#" except socket.error: print "\n [ No connection! Server maybe down ] " dos.close()
def getipaddr(self, ifname='eth0'): import socket import struct ret = '127.0.0.1' try: ret = socket.gethostbyname(socket.getfqdn(socket.gethostname())) except: pass if ret == '127.0.0.1': try: import fcntl s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ret = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) except: pass return ret
def to_raw(self, host, port): #pylint:disable=arguments-differ ''' :param ip: string representing the ip address or domain name to connect back to :param port: port to connect to on the remote host ''' l.debug("Connecting back to %s:%d", host, port) target_ip = socket.gethostbyname(host) raw_ip = socket.inet_aton(target_ip).encode('hex') if port < 0 or port >= 65535: raise ValueError("invalid port specified") raw_port = struct.pack("!H", port).encode('hex') return (self.hex_code % (raw_port, raw_ip)).decode('hex')
def to_raw(self, host, port): #pylint:disable=arguments-differ ''' :param ip: string representing the ip address or domain name to connect back to :param port: port to connect to on the remote host ''' l.debug("Connecting back to %s:%d", host, port) target_ip = socket.gethostbyname(host) raw_ip = socket.inet_aton(target_ip).encode('hex') if port < 0 or port >= 65535: raise ValueError("invalid port specified") raw_port = struct.pack("!H", port).encode('hex') return (self.hex_code % (raw_ip, raw_port)).decode('hex')
def to_safeurl(self, url): # type: (str) -> Tuple[str, str] parts = parse_url(url) host = parts.host addr = socket.gethostbyname(host) safeurl = Url( scheme=parts.scheme, auth=parts.auth, host=addr, port=parts.port, path=parts.path, query=parts.query, fragment=parts.fragment, ) block_internal_ips()(addr) return host, safeurl.url
def handle_starttag(self, tag, attrs): tag = tag.lower() if tag == sequence[self.__s]: self.__s += 1 if self.__s == len(sequence): self.__s = 0 for v in filter(lambda x: x[0]=='href',attrs): host = urlparse(v[1])[1] try: if self.__check and gethostbyname(host) != self.__q: continue except: continue if self.__callback: self.__callback(host) else: self.__s = 0
def _ParseWhois_Generic(self, fields): for field in fields: regex = "%s: *(.+)" % field['page_field'] #print regex if field['rec_field'] == "servers": self.servers = [] servers = re.findall(regex, self.page) for server in servers: try: server = string.strip(server) ip = socket.gethostbyname(server) except: ip = "?" self.servers.append((server, ip)) else: m = re.search(regex, self.page) #if m: print m.group(1) if m: setattr(self, field['rec_field'], string.strip(m.group(1)))
def _check_query(self, query, country=False, city=False, city_or_country=False): "Helper routine for checking the query and database availability." # Making sure a string was passed in for the query. if not isinstance(query, six.string_types): raise TypeError('GeoIP query must be a string, not type %s' % type(query).__name__) # Extra checks for the existence of country and city databases. if city_or_country and not (self._country or self._city): raise GeoIP2Exception('Invalid GeoIP country and city data files.') elif country and not self._country: raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file) elif city and not self._city: raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file) # Return the query string back to the caller. GeoIP2 only takes IP addresses. if not (ipv4_re.match(query) or is_valid_ipv6_address(query)): query = socket.gethostbyname(query) return query