Python ipaddress.ip_address() Examples
The following are 30
code examples of ipaddress.ip_address().
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
ipaddress
, or try the search function
.
Example #1
Source File: iscdn.py From Vxscan with Apache License 2.0 | 6 votes |
def iscdn(host): result = True # noinspection PyBroadException try: if not re.search(r'\d+\.\d+\.\d+\.\d+', host): host = parse_ip(host) for cdn in cdns: if ipaddress.ip_address(host) in ipaddress.ip_network(cdn): result = False except Exception: pass # noinspection PyBroadException try: with geoip2.database.Reader('data/GeoLite2-ASN.mmdb') as reader: response = reader.asn(host) for i in ASNS: if response.autonomous_system_number == int(i): result = False except Exception: pass return result
Example #2
Source File: helpers.py From panoptes with Apache License 2.0 | 6 votes |
def transform_index_ipv6_address(ipv6_str): """ Converts a substring of an SNMP index that contains an IPv6 address into a human readable format. Example: 254.128.0.0.0.0.0.0.14.134.16.255.254.243.135.30 => fe80::e86:10ff:fef3:871e Args: ipv6_str (str): SNMP index substring containing an IPv6 address. Returns: str: human readable IPv6 address """ parts = [u"{0:02x}".format(int(x)) for x in ipv6_str.split(u'.')] byte_string = u"" for p, i in enumerate(parts): if p % 2 != 0: byte_string += u'{}{}:'.format(parts[p - 1].lstrip(u'0'), parts[p]) result = str(byte_string[:-1]) if isinstance(result, bytes): result = result.decode('utf-8') return str(ipaddress.ip_address(result))
Example #3
Source File: plugin_enrichment_bgp_session_metrics.py From panoptes with Apache License 2.0 | 6 votes |
def transform_ip_octstr(ip_octstr): """ Converts octet strings containing IPv4 or IPv6 addresses into a human readable format. Args: ip_octstr (str): The octet string returned via SNMP Returns: str: human readable IPv4 or IPv6 IP address: 2001:dea:0:10::82, 1.2.3.4 """ if isinstance(ip_octstr, bytes) and not is_python_2(): byte_arr = [u'{:02x}'.format(_) for _ in ip_octstr] else: byte_arr = ['%0.2x' % ord(_) for _ in ip_octstr] if len(byte_arr) == 4: return '.'.join([str(int(x, 16)) for x in byte_arr]) else: byte_string = "" for p, i in enumerate(byte_arr): if p % 2 != 0: byte_string += '{}{}:'.format(byte_arr[p - 1].lstrip('0'), byte_arr[p]) # ipaddress formats the string nicely -- collapses blocks of zero return str(ipaddress.ip_address(byte_string[:-1].encode('ascii').decode('ascii')))
Example #4
Source File: urlutils.py From qutebrowser with GNU General Public License v3.0 | 6 votes |
def _is_url_naive(urlstr: str) -> bool: """Naive check if given URL is really a URL. Args: urlstr: The URL to check for, as string. Return: True if the URL really is a URL, False otherwise. """ url = qurl_from_user_input(urlstr) assert url.isValid() host = url.host() # Valid IPv4/IPv6 address. Qt converts things like "23.42" or "1337" or # "0xDEAD" to IP addresses, which we don't like, so we check if the host # from Qt is part of the input. if (not utils.raises(ValueError, ipaddress.ip_address, host) and host in urlstr): return True tld = r'\.([^.0-9_-]+|xn--[a-z0-9-]+)$' forbidden = r'[\u0000-\u002c\u002f\u003a-\u0060\u007b-\u00b6]' return bool(re.search(tld, host) and not re.search(forbidden, host))
Example #5
Source File: test_common.py From service-identity with MIT License | 6 votes |
def test_ip_address_success(self): """ IP addresses patterns are matched against IP address IDs. """ ip4 = ipaddress.ip_address(u"2.2.2.2") ip6 = ipaddress.ip_address(u"2a00:1c38::53") id4 = IPAddress_ID(six.text_type(ip4)) id6 = IPAddress_ID(six.text_type(ip6)) rv = verify_service_identity( extract_ids(CERT_EVERYTHING), [id4, id6], [] ) assert [ ServiceMatch(id4, IPAddressPattern(ip4)), ServiceMatch(id6, IPAddressPattern(ip6)), ] == rv
Example #6
Source File: linux_mips32_connectback.py From rex with BSD 2-Clause "Simplified" License | 6 votes |
def raw(self, arch=None): if not arch: raise ValueError("Architecture must be specified.") the_arch = convert_arch(arch) if the_arch.name != "MIPS32": raise TypeError("%s only supports MIPS32." % str(self.__class__)) packed_port = struct.pack('>H', (~self.port) & 0xffff) target_ip = socket.gethostbyname(self.host) ip = ipaddress.ip_address(target_ip) ip_for_shellcode = (~int(ip)) & 0xffffffff ip_to_send = struct.pack('>I', ip_for_shellcode) lower_ip = ip_to_send[:2] higher_ip = ip_to_send[2:] if the_arch.memory_endness == Endness.LE: return self.code_le % (packed_port, higher_ip, lower_ip) else: raise NOTIMPLEMENTEDYET()
Example #7
Source File: clients.py From kuryr-kubernetes with Apache License 2.0 | 6 votes |
def setup_kubernetes_client(): if config.CONF.kubernetes.api_root: api_root = config.CONF.kubernetes.api_root else: # NOTE(dulek): This is for containerized deployments, i.e. running in # K8s Pods. host = os.environ['KUBERNETES_SERVICE_HOST'] port = os.environ['KUBERNETES_SERVICE_PORT_HTTPS'] try: addr = ipaddress.ip_address(host) if addr.version == 6: host = '[%s]' % host except ValueError: # It's not an IP addres but a hostname, it's fine, move along. pass api_root = "https://%s:%s" % (host, port) _clients[_KUBERNETES_CLIENT] = k8s_client.K8sClient(api_root)
Example #8
Source File: monitoring.py From pyquarkchain with MIT License | 6 votes |
def fetch_peers_async(node): """ :param node: tuple(ip, p2p_port, jrpc_port) :return: list of tuple(ip, p2p_port, jrpc_port) """ json_rpc_url = "http://{}:{}".format(node[0], node[2]) server = Server(json_rpc_url) try: peers = await asyncio.wait_for(server.get_peers(), 5) except Exception: print("Failed to get peers from {}".format(json_rpc_url)) peers = {"peers": []} await server.session.close() return [ ( str(ipaddress.ip_address(int(p["ip"], 16))), int(p["port"], 16), int(p["port"], 16) + node[2] - node[1], ) for p in peers["peers"] ]
Example #9
Source File: utility.py From scantron with Apache License 2.0 | 6 votes |
def expand_range_of_ips(start_ip, end_ip): """Takes an IP range and returns all the IPs in that range. # http://cmikavac.net/2011/09/11/how-to-generate-an-ip-range-list-in-python/ """ ip_range = [] if (ipaddress.ip_address(start_ip).version == 6) or (ipaddress.ip_address(end_ip).version == 6): print("IPv6 IP range not supported in this function: {} - {}".format(start_ip, end_ip)) return ip_range start = list(map(int, start_ip.split("."))) end = list(map(int, end_ip.split("."))) temp = start ip_range.append(start_ip) while temp != end: start[3] += 1 for i in (3, 2, 1): if temp[i] == 256: temp[i] = 0 temp[i - 1] += 1 ip_range.append(".".join(map(str, temp))) return ip_range
Example #10
Source File: evil_ssdp.py From evil-ssdp with MIT License | 6 votes |
def set_smb(args, local_ip): """ This function sets the IP address of the SMB server that will be used in the phishing page. evil-ssdp does not provide an SMB server itself - it only points somewhere. You must host your own SMB server with something like Impacket. """ if args.smb: if ip_address(args.smb): smb_server = args.smb else: print("Sorry, that is not a valid IP address for your SMB server.") sys.exit() else: smb_server = local_ip return smb_server
Example #11
Source File: mail.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _build_urls(self, page, path, hostname=None): urls = [] if not hostname: for address in self.config['server_config']['server.addresses']: ip = ipaddress.ip_address(address['host']) if not ip.is_unspecified and (ip.is_global or ip.is_private): hostname = address['host'] if not hostname: return if path == '.': landing_page = page else: landing_page = path + page urls.append([urllib.parse.urljoin('http://' + hostname, landing_page)]) if self._server_uses_ssl: urls.append([urllib.parse.urljoin('https://' + hostname, landing_page)]) return urls
Example #12
Source File: analyzer.py From Vxscan with Apache License 2.0 | 6 votes |
def get_cidr(iplist): cidrs = [] for ip in iplist: cidr = re.sub(r'\d+$', '0/24', ip) cidrs.append(ipaddress.ip_network(cidr)) result = [] for cidr in cidrs: for i in iplist: ip = ipaddress.ip_address(i) if ip in cidr: result.append(str(cidr)) break out = get_top(result) for i in out: cidr, num = i.split('|') print(cidr, num)
Example #13
Source File: server.py From sanic with MIT License | 6 votes |
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket: """Create TCP server socket. :param host: IPv4, IPv6 or hostname may be specified :param port: TCP port number :param backlog: Maximum number of connections to queue :return: socket.socket object """ try: # IP address: family must be specified for IPv6 at least ip = ip_address(host) host = str(ip) sock = socket.socket( socket.AF_INET6 if ip.version == 6 else socket.AF_INET ) except ValueError: # Hostname, may become AF_INET or AF_INET6 sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port)) sock.listen(backlog) return sock
Example #14
Source File: nat.py From pyquarkchain with MIT License | 6 votes |
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str: """ For a given UPnP device, return the internal IP address of this host machine that can be used for a NAT mapping. """ parsed_url = urlparse(upnp_dev.location) # Get an ipaddress.IPv4Network instance for the upnp device's network. upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False) for iface in netifaces.interfaces(): for family, addresses in netifaces.ifaddresses(iface).items(): # TODO: Support IPv6 addresses as well. if family != netifaces.AF_INET: continue for item in addresses: if ipaddress.ip_address(item["addr"]) in upnp_dev_net: return item["addr"] raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname)
Example #15
Source File: http.py From tomodachi with MIT License | 6 votes |
def get_request_ip(request: Any, context: Optional[Dict] = None) -> Optional[str]: if request._cache.get('request_ip'): return str(request._cache.get('request_ip', '')) if request.transport: if not context: context = {} real_ip_header = context.get('options', {}).get('http', {}).get('real_ip_header', 'X-Forwarded-For') real_ip_from = context.get('options', {}).get('http', {}).get('real_ip_from', []) if isinstance(real_ip_from, str): real_ip_from = [real_ip_from] peername = request.transport.get_extra_info('peername') request_ip = None if peername: request_ip, _ = peername if real_ip_header and real_ip_from and request.headers.get(real_ip_header) and request_ip and len(real_ip_from): if any([ipaddress.ip_address(request_ip) in ipaddress.ip_network(cidr) for cidr in real_ip_from]): request_ip = request.headers.get(real_ip_header).split(',')[0].strip().split(' ')[0].strip() request._cache['request_ip'] = request_ip return request_ip return None
Example #16
Source File: cspcheck_ipsource.py From securityheaders with Apache License 2.0 | 6 votes |
def checkIP(self, directive, directiveValues, findings): csp = self.csp for value in directiveValues: url = '//' + Util.getSchemeFreeUrl(value) host = urlparse(url).netloc ip = None validip = True try: ip = ipaddress.ip_address(u''+host) except ValueError: validip = False if validip: ipString = str(ip) + '' if '127.0.0.1' in ipString: findings.append(Finding(csp.headerkey,FindingType.IP_SOURCE, directive.value + ' directive allows localhost as source. Please make sure to remove this in production environments.',FindingSeverity.INFO, directive, value)) else: findings.append(Finding(csp.headerkey,FindingType.IP_SOURCE, directive.value + ' directive has an IP-Address as source: ' + ipString + ' (will be ignored by browsers!). ', FindingSeverity.INFO, directive, value))
Example #17
Source File: forms.py From django-payfast with MIT License | 6 votes |
def is_payfast_ip_address(ip_address_str): """ Return True if ip_address_str matches one of PayFast's server IP addresses. Setting: `PAYFAST_IP_ADDRESSES` :type ip_address_str: str :rtype: bool """ # TODO: Django system check for validity? payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES', conf.DEFAULT_PAYFAST_IP_ADDRESSES) if sys.version_info < (3,): # Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors. # (On Python 3, this should generally not happen: # let unexpected bytes values fail as expected.) ip_address_str = unicode(ip_address_str) # noqa: F821 payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses] # noqa: F821 return any(ip_address(ip_address_str) in ip_network(payfast_address) for payfast_address in payfast_ip_addresses)
Example #18
Source File: action.py From insightconnect-plugins with MIT License | 6 votes |
def _match_whitelist(self, address: str, whitelist: str) -> bool: trimmed_address = re.sub(r"/32$", "", address) if address in whitelist: raise PluginException( cause=f"Address Object not created because the host {address} was found in the whitelist as {address}.", assistance=f"If you would like to block this host, remove {address} from the whitelist and try again.") elif '/' not in trimmed_address: pass for address_object in whitelist: if self._determine_address_type(address_object) == "cidr": net = ip_network(address_object, False) ip = ip_address(trimmed_address) if ip in net: raise PluginException( cause=f"Address Object not created because the host {address}" f" was found in the whitelist as {address_object}.", assistance="If you would like to block this host," f" remove {address_object} from the whitelist and try again.") return False
Example #19
Source File: access-handler.py From aws-waf-security-automations with Apache License 2.0 | 6 votes |
def waf_update_ip_set(ip_set_id, source_ip): logging.getLogger().debug('[waf_update_ip_set] Start') ip_type = "IPV%s"%ip_address(source_ip).version ip_class = "32" if ip_type == "IPV4" else "128" waf.update_ip_set(IPSetId=ip_set_id, ChangeToken=waf.get_change_token()['ChangeToken'], Updates=[{ 'Action': 'INSERT', 'IPSetDescriptor': { 'Type': ip_type, 'Value': "%s/%s"%(source_ip, ip_class) } }] ) logging.getLogger().debug('[waf_update_ip_set] End')
Example #20
Source File: extract_targets.py From scantron with Apache License 2.0 | 5 votes |
def is_valid_fqdn(self, domain): """Test if a provided domain is a valid FQDN.""" is_valid_fqdn = fqdn.FQDN(domain).is_valid return is_valid_fqdn # def expand_range_of_ips(self, start_ip, end_ip): # """Takes an IP range and returns all the IPs in that range. # # http://cmikavac.net/2011/09/11/how-to-generate-an-ip-range-list-in-python/ # """ # ip_range = [] # if (ipaddress.ip_address(start_ip).version == 6) or (ipaddress.ip_address(end_ip).version == 6): # print(f"IPv6 IP range not supported in this function: {start_ip} - {end_ip}") # return ip_range # start = list(map(int, start_ip.split("."))) # end = list(map(int, end_ip.split("."))) # temp = start # ip_range.append(start_ip) # while temp != end: # start[3] += 1 # for i in (3, 2, 1): # if temp[i] == 256: # temp[i] = 0 # temp[i - 1] += 1 # ip_range.append(".".join(map(str, temp))) # return ip_range
Example #21
Source File: aio_ips2firewall_v0.py From dashboard-api-python with MIT License | 5 votes |
def analyzeOrganization(aiomeraki: meraki.aio.AsyncDashboardAPI, orgId:str, days:int) -> Dict[str,int]: ret = {} timespan = days * 24 * 60 * 60 events = await aiomeraki.security_events.getOrganizationSecurityEvents(orgId, timespan=timespan,total_pages=-1) for e in events: ip, port = e["srcIp"].rsplit(":",1) ip = ip.strip("[]") # remove brackets in case of ipv6 if not ipaddress.ip_address(ip).is_private: # dont block private ip addresses on the public ip of the firewall ret[ip] = ret.get(ip, 0) + 1 return ret
Example #22
Source File: extract_targets.py From scantron with Apache License 2.0 | 5 votes |
def is_ip_address(self, ip): """Takes an IP address returns True/False if it is a valid IPv4 or IPv6 address.""" ip = str(ip) try: ipaddress.ip_address(ip) return True except ValueError: return False
Example #23
Source File: util.py From insightconnect-plugins with MIT License | 5 votes |
def match_whitelist(self, address: str, whitelist: list) -> bool: """ Checks to see if the address is in the white list :param address: An IP mask or a FQDN :param whitelist: A list of IP masks and FQDN's to check against :return: If the address was in the whitelist """ object_type = self.determine_address_type(address) if object_type == "fqdn": if address in whitelist: self.logger.info(f" Whitelist matched. {address} was found in whitelist") return True else: return False # if 1.1.1.1/32 - remove /32 trimmed_address = re.sub(r"/32$", "", address) # if contains / we compare explicit matches, but not subnets in subnets if '/' in trimmed_address: return address in whitelist # IP is in CIDR - Give the user a log message for item in whitelist: type_ = self.determine_address_type(item) if type_ == "ipmask": net = ip_network(item, False) # False means ignore the masked bits, otherwise they need to be 0 ip = ip_address(trimmed_address) if ip in net: self.logger.info(f" Whitelist matched\nIP {address} was found in {item}") return True return False
Example #24
Source File: network.py From tattle with Mozilla Public License 2.0 | 5 votes |
def default_ip_address(): """ Return the IP address of the first interface with a real IP addresses """ devices = netifaces.interfaces() for device in devices: addresses = netifaces.ifaddresses(device) if netifaces.AF_INET in addresses: for addr in addresses[netifaces.AF_INET]: ip_addr = ipaddress.ip_address(addr['addr']) if not ip_addr.is_loopback and (ip_addr.is_global or ip_addr.is_private): return str(ip_addr) return None
Example #25
Source File: monitoring.py From pyquarkchain with MIT License | 5 votes |
def fetch_peers(ip, jrpc_port): json_rpc_url = "http://{}:{}".format(ip, jrpc_port) print("calling {}".format(json_rpc_url)) peers = jsonrpcclient.request(json_rpc_url, "getPeers") return [ "{}:{}".format(ipaddress.ip_address(int(p["ip"], 16)), int(p["port"], 16)) for p in peers["peers"] ]
Example #26
Source File: simple_network.py From pyquarkchain with MIT License | 5 votes |
def __init__(self, env, master_server, loop): self.loop = loop self.env = env self.active_peer_pool = dict() # peer id => peer self.self_id = random_bytes(32) self.master_server = master_server master_server.network = self self.ip = ipaddress.ip_address(socket.gethostbyname(socket.gethostname())) self.port = self.env.cluster_config.P2P_PORT # Internal peer id in the cluster, mainly for connection management # 0 is reserved for master self.next_cluster_peer_id = 0 self.cluster_peer_pool = dict() # cluster peer id => peer
Example #27
Source File: kademlia.py From pyquarkchain with MIT License | 5 votes |
def __init__(self, ip: str, udp_port: int, tcp_port: int = 0) -> None: tcp_port = tcp_port or udp_port self.udp_port = udp_port self.tcp_port = tcp_port self._ip = ipaddress.ip_address(ip)
Example #28
Source File: wordlist_helper.py From VHostScan with GNU General Public License v3.0 | 5 votes |
def valid_ip(self, address): try: return ip_address(address) is not None except: return False
Example #29
Source File: action.py From insightconnect-plugins with MIT License | 5 votes |
def _check_if_private(address: str, address_type: str) -> bool: if address_type == "ipv6": ip_list = [str(ip) for ip in IPv6Network(address)] else: ip_list = [str(ip) for ip in IPv4Network(address)] if ip_address(ip_list[0]).is_private and ip_address(ip_list[-1]).is_private: return True return False
Example #30
Source File: allowed_address_pairs.py From octavia with Apache License 2.0 | 5 votes |
def _get_ethertype_for_ip(self, ip): address = ipaddress.ip_address(ip) return 'IPv6' if address.version == 6 else 'IPv4'