def str_to_int(addr): """ :param addr: An IEEE EUI-64 indentifier in string form. :return: An unsigned integer that is equivalent to value represented by EUI-64 string address formatted according to the dialect """ words = [] try: words = _get_match_result(addr, RE_EUI64_FORMATS) if not words: raise TypeError except TypeError: raise AddrFormatError('invalid IEEE EUI-64 identifier: %r!' % addr) if isinstance(words, tuple): pass else: words = (words, ) if len(words) == 8: # 2 bytes x 8 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 4: # 4 bytes x 4 (Cisco like) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 16 bytes (bare, no delimiters) int_val = int('%016x' % int(words[0], 16), 16) else: raise AddrFormatError('bad word count for EUI-64 identifier: %r!' % addr) return int_val
def _set_value(self, value): if self._module is None: # EUI version is implicit, detect it from value. for module in (_eui48, _eui64): try: self._value = module.str_to_int(value) self._module = module break except AddrFormatError: try: if 0 <= int(value) <= module.max_int: self._value = int(value) self._module = module break except ValueError: pass if self._module is None: raise AddrFormatError('failed to detect EUI version: %r' % value) else: # EUI version is explicit. if hasattr(value, 'upper'): try: self._value = self._module.str_to_int(value) except AddrFormatError: raise AddrFormatError('address %r is not an EUIv%d' % (value, self._module.version)) else: if 0 <= int(value) <= self._module.max_int: self._value = int(value) else: raise AddrFormatError('bad address format: %r' % value)
def str_to_int(addr): """ @param addr: An IPv6 address in string form. @return: The equivalent unsigned integer for a given IPv6 address. """ if addr == '': raise AddrFormatError('Empty strings are not supported!') try: packed_int = _inet_pton(AF_INET6, addr) return packed_to_int(packed_int) except Exception: raise AddrFormatError('%r is not a valid IPv6 address string!' \ % addr)
def iter_nmap_range(iprange): """ The nmap security tool supports a custom type of IPv4 range using multiple hyphenated octets. This generator provides iterators yielding IP addresses according to this rule set. @param iprange: an nmap-style IP address range. @return: an iterator producing IPAddress objects for each IP in the range. """ if not valid_nmap_range(iprange): raise AddrFormatError('invalid nmap range: %s' % iprange) matrix = [] tokens = iprange.split('.') for token in tokens: if '-' in token: octets = token.split('-', 1) pair = (int(octets[0]), int(octets[1])) else: pair = (int(token), int(token)) matrix.append(pair) for w in range(matrix[0][0], matrix[0][1] + 1): for x in range(matrix[1][0], matrix[1][1] + 1): for y in range(matrix[2][0], matrix[2][1] + 1): for z in range(matrix[3][0], matrix[3][1] + 1): yield IPAddress("%d.%d.%d.%d" % (w, x, y, z))
def valid_str(addr, flags=0): """ :param addr: An IPv4 address in presentation (string) format. :param flags: decides which rules are applied to the interpretation of the addr value. Supported constants are INET_PTON and ZEROFILL. See the netaddr.core docs for details. :return: ``True`` if IPv4 address is valid, ``False`` otherwise. """ if addr == '': raise AddrFormatError('Empty strings are not supported!') validity = True if flags & ZEROFILL: addr = '.'.join(['%d' % int(i) for i in addr.split('.')]) try: if flags & INET_PTON: _inet_pton(AF_INET, addr) else: _inet_aton(addr) except Exception: validity = False return validity
def glob_to_iptuple(ipglob): """ A function that accepts a glob-style IP range and returns the component lower and upper bound IP address. :param ipglob: an IP address range in a glob-style format. :return: a tuple contain lower and upper bound IP objects. """ if not valid_glob(ipglob): raise AddrFormatError('not a recognised IP glob range: %r!' % ipglob) start_tokens = [] end_tokens = [] for octet in ipglob.split('.'): if '-' in octet: tokens = octet.split('-') start_tokens.append(tokens[0]) end_tokens.append(tokens[1]) elif octet == '*': start_tokens.append('0') end_tokens.append('255') else: start_tokens.append(octet) end_tokens.append(octet) return IPAddress('.'.join(start_tokens)), IPAddress('.'.join(end_tokens))
def glob_to_iprange(ipglob): """ A function that accepts a glob-style IP range and returns the equivalent IP range. :param ipglob: an IP address range in a glob-style format. :return: an IPRange object. """ if not valid_glob(ipglob): raise AddrFormatError('not a recognised IP glob range: %r!' % ipglob) start_tokens = [] end_tokens = [] for octet in ipglob.split('.'): if '-' in octet: tokens = octet.split('-') start_tokens.append(tokens[0]) end_tokens.append(tokens[1]) elif octet == '*': start_tokens.append('0') end_tokens.append('255') else: start_tokens.append(octet) end_tokens.append(octet) return IPRange('.'.join(start_tokens), '.'.join(end_tokens))
def str_to_int(addr): """ :param addr: An IEEE EUI-48 (MAC) address in string form. :return: An unsigned integer that is equivalent to value represented by EUI-48/MAC string address formatted according to the dialect settings. """ words = [] if _is_str(addr): found_match = False for regexp in RE_MAC_FORMATS: match_result = regexp.findall(addr) if len(match_result) != 0: found_match = True if isinstance(match_result[0], tuple): words = match_result[0] else: words = (match_result[0], ) break if not found_match: raise AddrFormatError('%r is not a supported MAC format!' % (addr, )) else: raise TypeError('%r is not str() or unicode()!' % (addr, )) int_val = None if len(words) == 6: # 2 bytes x 6 (UNIX, Windows, EUI-48) int_val = int(''.join(['%.2x' % int(w, 16) for w in words]), 16) elif len(words) == 3: # 4 bytes x 3 (Cisco) int_val = int(''.join(['%.4x' % int(w, 16) for w in words]), 16) elif len(words) == 2: # 6 bytes x 2 (PostgreSQL) int_val = int(''.join(['%.6x' % int(w, 16) for w in words]), 16) elif len(words) == 1: # 12 bytes (bare, no delimiters) int_val = int('%012x' % int(words[0], 16), 16) else: raise AddrFormatError('unexpected word count in MAC address %r!' % (addr, )) return int_val
def str_to_int(addr): """ @param addr: An IPv4 dotted decimal address in string form. @return: The equivalent unsigned integer for a given IPv4 address. """ if addr == '': raise AddrFormatError('Empty strings are not supported!') try: return _struct.unpack('>I', _inet_aton(addr))[0] except: # Windows platform workaround. if hasattr(addr, 'lower') and _platform.system() == 'Windows': if addr.lower() == '0xffffffff': return 0xffffffff raise AddrFormatError('%r is not a valid IPv4 address string!' \ % addr)
def _parse_nmap_target_spec(target_spec): if '/' in target_spec: _, prefix = target_spec.split('/', 1) if not (0 < int(prefix) < 33): raise AddrFormatError('CIDR prefix expected, not %s' % prefix) net = IPNetwork(target_spec) if net.version != 4: raise AddrFormatError('CIDR only support for IPv4!') for ip in net: yield ip elif ':' in target_spec: # nmap only currently supports IPv6 addresses without prefixes. yield IPAddress(target_spec) else: octet_ranges = _generate_nmap_octet_ranges(target_spec) for w in octet_ranges[0]: for x in octet_ranges[1]: for y in octet_ranges[2]: for z in octet_ranges[3]: yield IPAddress("%d.%d.%d.%d" % (w, x, y, z), 4)
def _generate_nmap_octet_ranges(nmap_target_spec): # Generate 4 lists containing all octets defined by a given nmap Target # specification. if not _is_str(nmap_target_spec): raise TypeError('string expected, not %s' % type(nmap_target_spec)) if not nmap_target_spec: raise ValueError('nmap target specification cannot be blank!') tokens = nmap_target_spec.split('.') if len(tokens) != 4: raise AddrFormatError('invalid nmap range: %s' % nmap_target_spec) if tokens[0] == '-': raise AddrFormatError('first octet cannot be a sole hyphen!') return (_nmap_octet_target_values(tokens[0]), _nmap_octet_target_values(tokens[1]), _nmap_octet_target_values(tokens[2]), _nmap_octet_target_values(tokens[3]))
def ip_check_routable(item): ip_addr = IPAddress(item) # This prevents netaddr allowing shortened ip addresses if not str(ip_addr) == item: raise AddrFormatError("IP Malformed {}".format(item)) # Check for reserved IP addresses if any([ ip_addr.is_multicast(), ip_addr.is_private(), ip_addr.is_loopback(), ip_addr.is_link_local(), ip_addr.is_reserved() ]): raise AddrFormatError("IP is reserved {}".format(item)) # Check to see if IP is IPv4 # elif ip_addr.version is not 4: # raise AddrFormatError("IP is not IPv4") return True
def test_cluster_network(self): self.patch_requires_class('_all_joined_units') self._all_joined_units.received.__getitem__.return_value = '192.0.2.1' self.patch_object(requires.ch_ip, 'resolve_network_cidr') self.resolve_network_cidr.return_value = '192.0.2.0/24' self.assertEqual(self.requires_class.cluster_network, '192.0.2.0/24') self._all_joined_units.received.__getitem__.assert_called_once_with( 'ceph-cluster-address') self.resolve_network_cidr.assert_called_once_with('192.0.2.1') # Test no netmask condition self.resolve_network_cidr.side_effect = AddrFormatError() self.assertEqual(self.requires_class.cluster_network, None)
def str_to_int(addr): """ :param addr: An IEEE EUI-64 indentifier in string form. :return: An unsigned integer that is equivalent to value represented by EUI-64 string identifier. """ words = [] try: words = _get_match_result(addr, RE_EUI64_FORMATS) if not words: raise TypeError except TypeError: raise AddrFormatError('invalid IEEE EUI-64 identifier: %r!' % addr) if _is_str(words): return int(words, 16) if len(words) != num_words: raise AddrFormatError('bad word count for EUI-64 identifier: %r!' \ % addr) return int(''.join(['%.2x' % int(w, 16) for w in words]), 16)
def str_to_int(addr, flags=0): """ :param addr: An IPv6 address in string form. :param flags: decides which rules are applied to the interpretation of the addr value. Future use - currently has no effect. :return: The equivalent unsigned integer for a given IPv6 address. """ try: packed_int = _inet_pton(AF_INET6, addr) return packed_to_int(packed_int) except Exception: raise AddrFormatError('%r is not a valid IPv6 address string!' % addr)
def valid_str(addr): """ @param addr: An IPv6 address in presentation (string) format. @return: C{True} if IPv6 address is valid, C{False} otherwise. """ if addr == '': raise AddrFormatError('Empty strings are not supported!') try: _inet_pton(AF_INET6, addr) except: return False return True
def valid_str(addr, flags=0): """ :param addr: An IPv6 address in presentation (string) format. :param flags: decides which rules are applied to the interpretation of the addr value. Future use - currently has no effect. :return: ``True`` if IPv6 address is valid, ``False`` otherwise. """ if addr == '': raise AddrFormatError('Empty strings are not supported!') try: _inet_pton(AF_INET6, addr) except: return False return True
def base85_to_ipv6(addr): """ Convert a base 85 IPv6 address to its hexadecimal format. """ tokens = list(addr) if len(tokens) != 20: raise AddrFormatError('Invalid base 85 IPv6 address: %r' % (addr, )) result = 0 for i, num in enumerate(reversed(tokens)): num = BASE_85_DICT[num] result += (num * 85**i) ip = IPAddress(result, 6) return str(ip)
def str_to_int(addr, flags=0): """ :param addr: An IPv4 dotted decimal address in string form. :param flags: decides which rules are applied to the interpretation of the addr value. Supported constants are INET_PTON and ZEROFILL. See the netaddr.core docs for details. :return: The equivalent unsigned integer for a given IPv4 address. """ if flags & ZEROFILL: addr = '.'.join(['%d' % int(i) for i in addr.split('.')]) try: if flags & INET_PTON: return _struct.unpack('>I', _inet_pton(AF_INET, addr))[0] else: return _struct.unpack('>I', _inet_aton(addr))[0] except: raise AddrFormatError('%r is not a valid IPv4 address string!' % addr)
def expand_partial_address(addr): """ Expands a partial IPv4 address into a full 4-octet version. :param addr: an partial or abbreviated IPv4 address :return: an expanded IP address in presentation format (x.x.x.x) """ tokens = [] error = AddrFormatError('invalid partial IPv4 address: %r!' % addr) if isinstance(addr, _str_type): if ':' in addr: # Ignore IPv6 ... raise error try: if '.' in addr: tokens = ['%d' % int(o) for o in addr.split('.')] else: tokens = ['%d' % int(addr)] except ValueError: raise error if 1 <= len(tokens) <= 4: for i in range(4 - len(tokens)): tokens.append('0') else: raise error if not tokens: raise error return '%s.%s.%s.%s' % tuple(tokens)