Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address.
(host: AnyStr)
| 9 | |
| 10 | |
| 11 | def is_valid_host(host: AnyStr) -> bool: |
| 12 | """ |
| 13 | Checks if the passed bytes are a valid DNS hostname or an IPv4/IPv6 address. |
| 14 | """ |
| 15 | if isinstance(host, str): |
| 16 | try: |
| 17 | host_bytes = host.encode("idna") |
| 18 | except UnicodeError: |
| 19 | return False |
| 20 | else: |
| 21 | host_bytes = host |
| 22 | try: |
| 23 | host_bytes.decode("idna") |
| 24 | except ValueError: |
| 25 | return False |
| 26 | # RFC1035: 255 bytes or less. |
| 27 | if len(host_bytes) > 255: |
| 28 | return False |
| 29 | if host_bytes and host_bytes.endswith(b"."): |
| 30 | host_bytes = host_bytes[:-1] |
| 31 | # DNS hostname |
| 32 | if all(_label_valid.match(x) for x in host_bytes.split(b".")): |
| 33 | return True |
| 34 | # IPv4/IPv6 address |
| 35 | try: |
| 36 | ipaddress.ip_address(host_bytes.decode("idna")) |
| 37 | return True |
| 38 | except ValueError: |
| 39 | return False |
| 40 | |
| 41 | |
| 42 | def is_valid_port(port: int) -> bool: |
no test coverage detected
searching dependent graphs…