def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return ipaddress.IPv4Address(address) except (ipaddress.AddressValueError, ipaddress.NetmaskValueError) as err: log.debug('Error while parsing IPv4 address: %s', address) log.debug(err) try: return IPv6AddressScoped(address) except (ipaddress.AddressValueError, ipaddress.NetmaskValueError) as err: log.debug('Error while parsing IPv6 address: %s', address) log.debug(err) if isinstance(address, bytes): raise ipaddress.AddressValueError('{} does not appear to be an IPv4 or IPv6 address. ' 'Did you pass in a bytes (str in Python 2) instead ' 'of a unicode object?'.format(repr(address))) raise ValueError('{} does not appear to be an IPv4 or IPv6 address'.format(repr(address)))
def parse(string): """Parses a string representation of a socket address. IPv4 syntax: <IPv4 address> ':' <port> IPv6 syntax: '[' <IPv6 address> ']' ':' <port> DNS syntax: <hostname> ':' <port> Raises AddressValueError if the input cannot be parsed. :param str string: :returns parsed SocketAddress :rtype SocketAddress """ if not isinstance(string, str): raise TypeError('Expected string argument, not ' + type(string).__name__) try: if string.startswith('['): # We expect '[<ip6 addr>]:<portnum>', # use ipaddress to parse IPv6 address: addr_str, port_str = string.split(']:') addr_str = addr_str[1:] else: # We expect '<ip4 addr or hostname>:<port>'. addr_str, port_str = string.split(':') port = int(port_str) except ValueError: raise ipaddress.AddressValueError( 'Invalid address "{}"'.format(string)) return SocketAddress(addr_str, port)
def chose_blacklist(self, ip): """ Given an IP address, figure out the set we have to use. If the address is an IPv4, we have to use *ellis_blacklist4*. If the address is an IPv6, we have to use *ellis_blacklist6*. Raises ipaddress.AddressValueError if the address is neither an IPv4 nor an IPv6. """ blacklist = 'ellis_blacklist{0}' try: address = ipaddress.ip_address(ip) except ipaddress.AddressValueError: raise else: if address.version is 6: # We don't ban private IPv6: if address.is_private: msg = "We don't ban private addresses ({0} given)." \ .format(address) raise ipaddress.AddressValueError(msg) else: # Do we have an embedded IPv4 ? if address.ipv4_mapped is not None: address = address.ipv4_mapped elif address.sixtofour is not None: address = address.sixtofour blacklist = blacklist.format(address.version) return (address, blacklist)
def from_ip(ip: Union[bytes, str]) -> TypeVar("InternetType"): if isinstance(ip, (bytes, str)): ip = ipaddress.ip_address(ip) if isinstance(ip, ipaddress.IPv4Address): return InternetType.IPv4 if isinstance(ip, ipaddress.IPv6Address): return InternetType.IPv6 raise ipaddress.AddressValueError()
def __init__(self, address): """ Instantiate a new IPv6 address object. Scope is moved to an attribute 'scope'. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. :param address: """ # pylint: disable-all if not hasattr(self, "_is_packed_binary"): # This method (below) won't be around for some Python 3 versions # and we need check this differently anyway self._is_packed_binary = lambda p: isinstance(p, bytes) # pylint: enable-all if isinstance(address, string_types) and "%" in address: buff = address.split("%") if len(buff) != 2: raise SaltException( 'Invalid IPv6 address: "{}"'.format(address)) address, self.__scope = buff else: self.__scope = None # For compatibility with python3.9 ipaddress self._scope_id = self.__scope if sys.version_info.major == 2: ipaddress._BaseAddress.__init__(self, address) ipaddress._BaseV6.__init__(self, address) else: # Python 3.4 fix. Versions higher are simply not affected # https://github.com/python/cpython/blob/3.4/Lib/ipaddress.py#L543-L544 self._version = 6 self._max_prefixlen = ipaddress.IPV6LENGTH # Efficient constructor from integer. if isinstance(address, integer_types): self._check_int_address(address) self._ip = address elif self._is_packed_binary(address): self._check_packed_address(address, 16) self._ip = int(binascii.hexlify(address), 16) else: address = str(address) if "/" in address: raise ipaddress.AddressValueError( "Unexpected '/' in {}".format(address)) self._ip = self._ip_int_from_string(address)
def __init__(self, address, port): """Creates and validates SocketAddress. Raises AddressValueError if 'address' or 'port' is invalid. :param str address: IPv4/IPv6 address or hostname :param int port: """ self.address = address self.port = port self.ipv6 = False self.hostname = False try: self.__validate() except ValueError as err: raise ipaddress.AddressValueError(err)
def __init__(self, address): ''' Instantiate a new IPv6 address object. Scope is moved to an attribute 'scope'. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address('2001:db8::') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address('2001:db8::'))) == IPv6Address('2001:db8::') Raises: AddressValueError: If address isn't a valid IPv6 address. :param address: ''' if isinstance(address, string_types) and '%' in address: buff = address.split('%') if len(buff) != 2: raise SaltException( 'Invalid IPv6 address: "{}"'.format(address)) address, self.__scope = buff else: self.__scope = None if sys.version_info.major == 2: ipaddress._BaseAddress.__init__(self, address) ipaddress._BaseV6.__init__(self, address) else: # Python 3.4 fix. Versions higher are simply not affected # https://github.com/python/cpython/blob/3.4/Lib/ipaddress.py#L543-L544 self._version = 6 self._max_prefixlen = ipaddress.IPV6LENGTH # Efficient constructor from integer. if isinstance(address, integer_types): self._check_int_address(address) self._ip = address elif self._is_packed_binary(address): self._check_packed_address(address, 16) self._ip = ipaddress._int_from_bytes(address, 'big') else: address = str(address) if '/' in address: raise ipaddress.AddressValueError( "Unexpected '/' in {}".format(address)) self._ip = self._ip_int_from_string(address)
def check_subnets(*ips) -> bool: """ Checks for valid IP Addresses or Subnet Parameters ---------- *ips ip addresses Returns ------- True if a subnet is found to set to networkMode, False if only hosts """ masks = set() for ip in ips: try: masks.add(ipaddress.IPv4Interface(ip).network.prefixlen) except (ipaddress.AddressValueError, ipaddress.NetmaskValueError): raise ipaddress.AddressValueError( f"{ip} is not a valid IP or subnet.") return True if masks != {32} else False
def find_ixp( ip: Union[str, IPv4Address, IPv6Address]) -> Tuple[str, _BaseNetwork]: """ Looks up a given IP address (as either a str, or ip_address object) in :py:attr:`.IX_NET_MAP` and returns either a tuple containing two ``fail_val`` items (if it's not found) or if found, a tuple containing the name of the IXP, and the subnet which contains this IP. Example usage:: >>> from lg.peerapp.settings import find_ixp >>> try: ... ix, subnet = find_ixp('192.168.1.5') ... print(f'{ix}, {subnet}') >>> except (IPNotFound, AddressValueError): ... print('Error! IP not found, or is invalid.') On success, outputs: EXMPL-IX, 192.168.1.0/24 :param str ip: An IP address, either as a ``str``, or a :py:func:`ipaddress.ip_address` object. :raises AddressValueError: When the given ``ip`` is not a valid IPv4/IPv6 address :raises IPNotFound: When the given ``ip`` was not found in :py:attr:`.IX_NET_MAP` :return tuple result: If the IP is found, will return a tuple ``(ixp_name: str, subnet: IPv4/v6Network, )`` """ ip = ipaddress.ip_address(ip) if not isinstance(ip, IPv4Address) and not isinstance(ip, IPv6Address): raise ipaddress.AddressValueError( f'Excepted IPv4/IPv6Address. Got {type(ip)}...') for l_net, l_ixp in IX_NET_VER[type(ip)]: l_net = ip_network(l_net) if ip in l_net: return l_ixp, l_net raise IPNotFound( f'IP Address "{ip}" was not found in the IXP network list.')
async def create_connection(loop: asyncio.BaseEventLoop, uri: str, mode: T.Optional[str] = 'diva' ) -> T.Tuple[asyncio.Transport, SliderDevice]: parsed_uri = urllib.parse.urlparse(uri) # tcp://127.0.0.1:12345 or tcp://[::1]:12345 if parsed_uri.scheme == 'tcp': return await loop.create_connection(lambda: SliderDevice(mode), parsed_uri.hostname, parsed_uri.port or 12345) # serial:COM0 or serial:///dev/ttyUSB0 or serial:/dev/ttyUSB0 elif parsed_uri.scheme == 'serial': return await serial_asyncio.create_serial_connection( loop, lambda: SliderDevice(mode), parsed_uri.path, baudrate=115200) # rfcomm://11-22-33-44-55-66:1 or rfcomm://11-22-33-44-55-66/sdp?[name=<name>][&uuid=<uuid>] or # rfcomm://[fe80::1122:33ff:fe44:5566]:1 or rfcomm://[fe80::1122:33ff:fe44:5566]/sdp?[name=<name>][&uuid=<uuid>] elif parsed_uri.scheme == 'rfcomm': if parsed_uri.path == '/sdp': if RFCOMM_URLSAFE_BDADDR.match(parsed_uri.hostname): bdaddr = parsed_uri.hostname.replace('-', ':') else: sixln_ipv6_addr = ipaddress.IPv6Address(parsed_uri.hostname) if not sixln_ipv6_addr.is_link_local: raise ipaddress.AddressValueError( '6LN IPv6 address must be a link-local address.') if sixln_ipv6_addr.packed[11:13] != b'\xff\xfe': raise ipaddress.AddressValueError( 'Invalid IID for 6LN IPv6 link-local address.') bdaddr = ':'.join( f'{b:02x}' for b in itertools.chain(sixln_ipv6_addr.packed[8:11], sixln_ipv6_addr.packed[13:16])) channel = None params = urllib.parse.parse_qs(parsed_uri.query) _logger.debug('SDP: Resolving service on %s', bdaddr) filter_ = {} if 'name' in params: filter_['name'] = params['name'][0] if 'uuid' in params: filter_['uuid'] = params['uuid'][0] services = bluetooth.find_service(address=bdaddr, **filter_) for svc in services: # TODO match classes? if bluetooth.SERIAL_PORT_CLASS in svc['service-classes']: _logger.debug('SDP: Found service "%s" on channel %d', svc['name'], svc['port']) channel = svc['port'] break if channel is None: raise ValueError('No matching service found') else: return await create_rfcomm_connection( loop, lambda: SliderDevice(mode), bdaddr, channel) elif parsed_uri.path != '/' and parsed_uri.path != '': raise ValueError('Unsupported URI {}'.format(uri)) else: return await create_rfcomm_connection( loop, lambda: SliderDevice(mode), parsed_uri.hostname.replace('-', ':'), parsed_uri.port or 1)