diff --git a/src/netcup_dns/main.py b/src/netcup_dns/main.py index fc695ce..693b255 100644 --- a/src/netcup_dns/main.py +++ b/src/netcup_dns/main.py @@ -93,31 +93,37 @@ def external_ipv4(timeout=5) -> str: # so we try these endpoints last. endpoints += ['https://ipinfo.io/ip'] - for endpoint in endpoints: - backup = None - try: - # Force the usage of IPv4 - # https://stackoverflow.com/a/72440253/6334421 - # - # Alternatively, use urllib3: https://stackoverflow.com/a/46972341/6334421 - backup = requests.packages.urllib3.util.connection.HAS_IPV6 - requests.packages.urllib3.util.connection.HAS_IPV6 = False + backup = None + try: + # Force the usage of IPv4. + # https://stackoverflow.com/a/72440253/6334421 + # + # Alternatively, use urllib3: https://stackoverflow.com/a/46972341/6334421 + backup = requests.packages.urllib3.util.connection.HAS_IPV6 + requests.packages.urllib3.util.connection.HAS_IPV6 = False + for endpoint in endpoints: # Timeout after 5 seconds. - ip = requests.get(endpoint, timeout=timeout).text.strip() + try: + ip = requests.get(endpoint, timeout=timeout).text.strip() + except requests.exceptions.RequestException: + continue + # Check if it is actually an IPv4 address. # Some services, such as e.g. v4.ident.me, sometimes return IPv6. - ipv4 = ipaddress.ip_address(ip) + try: + ipv4 = ipaddress.ip_address(ip) + except ValueError: + continue if not isinstance(ipv4, ipaddress.IPv4Address): continue + # Return ip address as string. return ipv4.exploded - except Exception as _e: - continue - finally: - # Allow usage of IPv6 again. - if backup is not None: - requests.packages.urllib3.util.connection.HAS_IPV6 = backup + finally: + if backup is not None: + requests.packages.urllib3.util.connection.HAS_IPV6 = backup + raise Exception('Could not determine public IPv4 address.')