check that an address string is valid Valid in this case means that a name is resolvable, or the IP address string is a correctly formed IPv4 or IPv6 address, with or without a port Args: addr (str): address Returns: Tuple[bool, str]: Validity of the address, ei
(addr: str)
| 57 | |
| 58 | |
| 59 | def valid_addr(addr: str) -> Tuple[bool, str]: |
| 60 | """check that an address string is valid |
| 61 | Valid in this case means that a name is resolvable, or the |
| 62 | IP address string is a correctly formed IPv4 or IPv6 address, |
| 63 | with or without a port |
| 64 | |
| 65 | Args: |
| 66 | addr (str): address |
| 67 | |
| 68 | Returns: |
| 69 | Tuple[bool, str]: Validity of the address, either |
| 70 | True, address type (IPv4[:Port], IPv6[:Port], Name[:Port]) |
| 71 | False, <error description> |
| 72 | """ |
| 73 | |
| 74 | def _dns_lookup(addr: str, port: Optional[int]) -> Tuple[bool, str]: |
| 75 | try: |
| 76 | socket.getaddrinfo(addr, None) |
| 77 | except socket.gaierror: |
| 78 | # not resolvable |
| 79 | return False, 'DNS lookup failed' |
| 80 | return True, 'Name:Port' if port else 'Name' |
| 81 | |
| 82 | def _ip_lookup(addr: str, port: Optional[int]) -> Tuple[bool, str]: |
| 83 | unwrapped = unwrap_ipv6(addr) |
| 84 | try: |
| 85 | ip_addr = ipaddress.ip_address(unwrapped) |
| 86 | except ValueError: |
| 87 | return False, 'Invalid IP v4 or v6 address format' |
| 88 | return True, f'IPv{ip_addr.version}:Port' if port else f'IPv{ip_addr.version}' |
| 89 | |
| 90 | dots = addr.count('.') |
| 91 | colons = addr.count(':') |
| 92 | addr_as_url = f'http://{addr}' |
| 93 | |
| 94 | if addr.startswith('[') and dots: |
| 95 | return False, "IPv4 address wrapped in brackets is invalid" |
| 96 | |
| 97 | try: |
| 98 | res = urlparse(addr_as_url) |
| 99 | except ValueError as e: |
| 100 | if str(e) == 'Invalid IPv6 URL': |
| 101 | return False, 'Address has incorrect/incomplete use of enclosing brackets' |
| 102 | return False, f'Unknown urlparse error {str(e)} for {addr_as_url}' |
| 103 | |
| 104 | addr = res.netloc |
| 105 | port = None |
| 106 | try: |
| 107 | port = res.port |
| 108 | if port: |
| 109 | addr = addr[:-len(f':{port}')] |
| 110 | except ValueError: |
| 111 | if colons == 1: |
| 112 | return False, 'Port must be numeric' |
| 113 | elif ']:' in addr: |
| 114 | return False, 'Port must be numeric' |
| 115 | |
| 116 | # catch partial address like 10.8 which would be valid IPaddress schemes |