feat: enhance external IP retrieval to explicitly fetch IPv4 if IPv6 is detected
Some checks failed
Ansible Lint Check / check-ansible (push) Failing after 12s
Nix Format Check / check-format (push) Successful in 44s
Python Lint Check / check-python (push) Failing after 10s

This commit is contained in:
Menno van Leeuwen 2025-03-26 14:43:04 +01:00
parent 24a33cfd08
commit 98690a5e70
Signed by: vleeuwenmenno
SSH Key Fingerprint: SHA256:OJFmjANpakwD3F2Rsws4GLtbdz1TJ5tkQF0RZmF0TRE

View File

@ -108,10 +108,10 @@ def get_external_ips():
""" """
Fetch both IPv4 and IPv6 external IP addresses of the machine. Fetch both IPv4 and IPv6 external IP addresses of the machine.
This function attempts to retrieve the external IP addresses using the services This function first attempts to retrieve an IP address using the services
`https://ifconfig.co`, `https://ifconfig.io`, and `https://ifconfig.me`. Each `https://ifconfig.co`, `https://ifconfig.io`, and `https://ifconfig.me`. If the
request has a timeout of 200ms to ensure speed. The user agent is explicitly first IP fetched is IPv6, it explicitly tries to fetch an IPv4 address using
set to `curl` to ensure proper response formatting. curl's `-4` option.
Returns: Returns:
tuple: A tuple containing the IPv4 and IPv6 addresses as strings. If either tuple: A tuple containing the IPv4 and IPv6 addresses as strings. If either
@ -128,11 +128,21 @@ def get_external_ips():
ip = response.text.strip() ip = response.text.strip()
if ":" in ip: # IPv6 address if ":" in ip: # IPv6 address
ipv6 = ip ipv6 = ip
# Try to fetch IPv4 explicitly
ipv4_response = subprocess.run(
["curl", "-4", "--silent", service],
capture_output=True,
text=True,
timeout=0.2,
check=True
)
if ipv4_response.returncode == 0:
ipv4 = ipv4_response.stdout.strip()
else: # IPv4 address else: # IPv4 address
ipv4 = ip ipv4 = ip
if ipv4 != "Unavailable" and ipv6 != "Unavailable": if ipv4 != "Unavailable" and ipv6 != "Unavailable":
break break
except requests.RequestException: except (requests.RequestException, subprocess.TimeoutExpired):
continue continue
return ipv4, ipv6 return ipv4, ipv6