我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用netaddr.AddrFormatError()。
def is_address_in_network(network, address): """ Determine whether the provided address is within a network range. :param network (str): CIDR presentation format. For example, '192.168.1.0/24'. :param address: An individual IPv4 or IPv6 address without a net mask or subnet prefix. For example, '192.168.1.1'. :returns boolean: Flag indicating whether address is in network. """ try: network = netaddr.IPNetwork(network) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Network (%s) is not in CIDR presentation format" % network) try: address = netaddr.IPAddress(address) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Address (%s) is not in correct presentation format" % address) if address in network: return True else: return False
def _parse_values(self, values): """ Parses values init arg. for responses with IPs fields. Similar parser as parent, but takes str & unicode fields and trys converting them to IPNetwork objects. """ for k, v in values.items(): if k != 'custom_fields': if isinstance(v, dict): lookup = getattr(self.__class__, k, None) if lookup: v = lookup(v, api_kwargs=self.api_kwargs) else: v = self.default_ret(v, api_kwargs=self.api_kwargs) if isinstance(v, six.string_types): try: v = netaddr.IPNetwork(v) except netaddr.AddrFormatError: pass self._add_cache((k, v)) else: self._add_cache((k, v.copy())) setattr(self, k, v)
def is_valid_cidr(address): """Verify that address represents a valid CIDR address. :param address: Value to verify :type address: string :returns: bool .. versionadded:: 3.8 """ try: # Validate the correct CIDR Address netaddr.IPNetwork(address) except (TypeError, netaddr.AddrFormatError): return False # Prior validation partially verify /xx part # Verify it here ip_segment = address.split('/') if (len(ip_segment) <= 1 or ip_segment[1] == ''): return False return True
def get_ip_network(ip_str): """ Try to return the owner of the IP address (based on ips.py) :param str ip_str: The IP address :rtype: str :return: The owner if find else None """ try: ip_addr = netaddr.IPAddress(ip_str) except (netaddr.AddrConversionError, netaddr.AddrFormatError): return None for brand, networks in IPS_NETWORKS.iteritems(): for net in networks: if net.netmask.value & ip_addr.value == net.value: return brand return None
def test_strategy_ipv6_str_to_int_behaviour_legacy_mode(): assert ipv6.str_to_int('::127') == 295 with pytest.raises(AddrFormatError): ipv6.str_to_int('::0x7f') assert ipv6.str_to_int('::0177') == 375 with pytest.raises(AddrFormatError): ipv6.str_to_int('::127.1') with pytest.raises(AddrFormatError): ipv6.str_to_int('::0x7f.1') with pytest.raises(AddrFormatError): ipv6.str_to_int('::0177.1') assert ipv6.str_to_int('::127.0.0.1') == 2130706433
def test_strategy_inet_pton_behaviour(): # inet_pton() is a newer system call that supports both IPv4 and IPv6. # It is a lot more strict about what it deems to be a valid IPv4 address # and doesn't support many of the features found in inet_aton() such as # support for non- decimal octets, partial numbers of octets, etc. with pytest.raises(AddrFormatError): ipv4.str_to_int('127', flags=INET_PTON) with pytest.raises(AddrFormatError): ipv4.str_to_int('0x7f', flags=INET_PTON) with pytest.raises(AddrFormatError): ipv4.str_to_int('0177', flags=INET_PTON) with pytest.raises(AddrFormatError): ipv4.str_to_int('127.1', flags=INET_PTON) with pytest.raises(AddrFormatError): ipv4.str_to_int('0x7f.1', flags=INET_PTON) with pytest.raises(AddrFormatError): ipv4.str_to_int('0177.1', flags=INET_PTON) assert ipv4.str_to_int('127.0.0.1', flags=INET_PTON) == 2130706433
def test_ipaddress_inet_pton_constructor_v4(): with pytest.raises(AddrFormatError): IPAddress('0177.01', flags=INET_PTON) with pytest.raises(AddrFormatError): IPAddress('0x7f.0.01', flags=INET_PTON) with pytest.raises(AddrFormatError): IPAddress('10', flags=INET_PTON) with pytest.raises(AddrFormatError): IPAddress('10.1', flags=INET_PTON) with pytest.raises(AddrFormatError): IPAddress('10.0.1', flags=INET_PTON) assert IPAddress('10.0.0.1', flags=INET_PTON) == IPAddress('10.0.0.1')
def test_iprange_constructor(): iprange = IPRange('192.0.2.1', '192.0.2.254') assert iprange == IPRange('192.0.2.1', '192.0.2.254') assert '%s' % iprange == '192.0.2.1-192.0.2.254' assert IPRange('::ffff:192.0.2.1', '::ffff:192.0.2.254') == IPRange('::ffff:192.0.2.1', '::ffff:192.0.2.254') assert IPRange('192.0.2.1', '192.0.2.1') == IPRange('192.0.2.1', '192.0.2.1') assert IPRange('208.049.164.000', '208.050.066.255', flags=ZEROFILL) == IPRange('208.49.164.0', '208.50.66.255') with pytest.raises(AddrFormatError): IPRange('192.0.2.2', '192.0.2.1') with pytest.raises(AddrFormatError): IPRange('::', '0.0.0.1') with pytest.raises(AddrFormatError): IPRange('0.0.0.0', '::1')
def get_ipv6_addr_by_EUI64(cidr, mac): """Generate a IPv6 addr by EUI-64 with CIDR and MAC :param str cidr: a IPv6 CIDR :param str mac: a MAC address :return: an IPv6 Address :rtype: netaddr.IPAddress """ # Check if the prefix is IPv4 address is_ipv4 = netaddr.valid_ipv4(cidr) if is_ipv4: msg = "Unable to generate IP address by EUI64 for IPv4 prefix" raise TypeError(msg) try: eui64 = int(netaddr.EUI(mac).eui64()) prefix = netaddr.IPNetwork(cidr) return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57)) except (ValueError, netaddr.AddrFormatError): raise TypeError('Bad prefix or mac format for generating IPv6 ' 'address by EUI-64: %(prefix)s, %(mac)s:' % {'prefix': cidr, 'mac': mac}) except TypeError: raise TypeError('Bad prefix type for generate IPv6 address by ' 'EUI-64: %s' % cidr)
def sendWoL(mac, broadcast=findBroadcast()): """Given string mac and broadcast: Turn on computer using WoL This was taken from http://code.activestate.com/recipes/358449-wake-on-lan/. Thanks, Fadly! """ # Cleans and removes delimiters from MAC try: mac = format_mac(EUI(mac), mac_bare) except AddrFormatError: raise ValueError('Incorrect MAC address format') # Pad the synchronization stream. data = ''.join(['FFFFFFFFFFFF', mac * 20]) send_data = b'' # Split up the hex values and pack. for i in range(0, len(data), 2): send_data = b''.join([send_data, pack('B', int(data[i: i + 2], 16))]) # Broadcast it to the LAN. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.sendto(send_data, (broadcast, 7))
def _validate_cidr_format(self, cidr, logger): """Validate that CIDR have a correct format. Example "10.10.10.10/24" :param str cidr: :param logging.Logger logger: :return: True/False whether CIDR is valid or not :rtype: bool """ try: netaddr.IPNetwork(cidr) except netaddr.AddrFormatError: logger.info("CIDR {} is in invalid format", exc_info=1) return False if '/' not in cidr: return False return True
def _to_mac_range(val): cidr_parts = val.split("/") prefix = cidr_parts[0] # FIXME(anyone): replace is slow, but this doesn't really # get called ever. Fix maybe? prefix = prefix.replace(':', '') prefix = prefix.replace('-', '') prefix_length = len(prefix) if prefix_length < 6 or prefix_length > 12: raise q_exc.InvalidMacAddressRange(cidr=val) diff = 12 - len(prefix) if len(cidr_parts) > 1: mask = int(cidr_parts[1]) else: mask = 48 - diff * 4 mask_size = 1 << (48 - mask) prefix = "%s%s" % (prefix, "0" * diff) try: cidr = "%s/%s" % (str(netaddr.EUI(prefix)).replace("-", ":"), mask) except netaddr.AddrFormatError: raise q_exc.InvalidMacAddressRange(cidr=val) prefix_int = int(prefix, base=16) return cidr, prefix_int, prefix_int + mask_size
def fallback_ip(self): if self._values['fallback_ip'] is None: return None if self._values['fallback_ip'] == 'any': return 'any' try: address = IPAddress(self._values['fallback_ip']) if address.version == 4: return str(address.ip) elif address.version == 6: return str(address.ip) return None except AddrFormatError: raise F5ModuleError( 'The provided fallback address is not a valid IPv4 address' )
def address(self, value): pattern = '^(?P<ip>[0-9A-Fa-f:.]+)%?(?P<rd>\d+)?\/(?P<nm>\d+)$' matches = re.match(pattern, value) if not matches: raise F5ModuleError( "The specified address is malformed. Please see documentation." ) try: ip = matches.group('ip') self._values['ip'] = str(IPAddress(ip)) except AddrFormatError: raise F5ModuleError( 'The provided address is not a valid IP address' ) self._values['route_domain'] = matches.group('rd') self._values['netmask'] = matches.group('nm')
def netmask(self): if self.want.netmask is None: return None try: address = IPNetwork(self.have.ip) if self.want.route_domain is not None: nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.want.netmask) cipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.have.netmask) elif self.have.route_domain is not None: nipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.want.netmask) cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.have.netmask) else: nipnet = "{0}/{1}".format(address.ip, self.want.netmask) cipnet = "{0}/{1}".format(address.ip, self.have.netmask) if nipnet != cipnet: return nipnet except AddrFormatError: raise F5ModuleError( 'The provided address/netmask value "{0}" was invalid'.format(self.have.ip) )
def route_domain(self): if self.want.route_domain is None: return None try: address = IPNetwork(self.have.ip) if self.want.netmask is not None: nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.want.netmask) cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.want.netmask) elif self.have.netmask is not None: nipnet = "{0}%{1}/{2}".format(address.ip, self.want.route_domain, self.have.netmask) cipnet = "{0}%{1}/{2}".format(address.ip, self.have.route_domain, self.have.netmask) if nipnet != cipnet: return nipnet except AddrFormatError: raise F5ModuleError( 'The provided address/netmask value was invalid' )
def fallback_ip(self): if self._values['fallback_ip'] is None: return None if self._values['fallback_ip'] == 'any': return 'any' if self._values['fallback_ip'] == 'any6': return 'any6' try: address = IPAddress(self._values['fallback_ip']) if address.version == 4: return str(address.ip) elif address.version == 6: return str(address.ip) return None except AddrFormatError: raise F5ModuleError( 'The provided fallback address is not a valid IPv4 address' )
def _validate_cidr(network): try: netaddr.IPNetwork(network) except (netaddr.core.AddrFormatError, ValueError): raise ValueError("Network (%s) is not in CIDR presentation format" % network)
def is_ipv6(address): """Determine whether provided address is IPv6 or not.""" try: address = netaddr.IPAddress(address) except netaddr.AddrFormatError: # probably a hostname - so not an address at all! return False return address.version == 6
def is_ip(address): """ Returns True if address is a valid IP address. """ try: # Test to see if already an IPv4/IPv6 address address = netaddr.IPAddress(address) return True except (netaddr.AddrFormatError, ValueError): return False
def test_ipv6_address_invalid(): with pytest.raises(netaddr.AddrFormatError): proxenos.node.ipv6_address('256.256.256.256', resolve=False)