feat: enhance external IP retrieval to support both IPv4 and IPv6 addresses
Some checks failed
Ansible Lint Check / check-ansible (push) Failing after 12s
Nix Format Check / check-format (push) Successful in 43s
Python Lint Check / check-python (push) Failing after 9s

This commit is contained in:
Menno van Leeuwen 2025-03-26 14:40:39 +01:00
parent 2c635164e7
commit 24a33cfd08
Signed by: vleeuwenmenno
SSH Key Fingerprint: SHA256:OJFmjANpakwD3F2Rsws4GLtbdz1TJ5tkQF0RZmF0TRE

View File

@ -104,28 +104,38 @@ def get_interface_state(interface):
except Exception:
return "UNKNOWN", "N/A"
def get_external_ip():
def get_external_ips():
"""
Fetch the external IP address of the machine.
Fetch both IPv4 and IPv6 external IP addresses of the machine.
This function attempts to retrieve the external IP address using the services
This function attempts to retrieve the external IP addresses using the services
`https://ifconfig.co`, `https://ifconfig.io`, and `https://ifconfig.me`. Each
request has a timeout of 200ms to ensure speed. The user agent is explicitly
set to `curl` to ensure proper response formatting.
Returns:
str: The external IP address if successful, or an error message if all services fail.
tuple: A tuple containing the IPv4 and IPv6 addresses as strings. If either
address cannot be fetched, it will be set to "Unavailable".
"""
services = ["https://ifconfig.co", "https://ifconfig.io", "https://ifconfig.me"]
headers = {"User-Agent": "curl"}
ipv4, ipv6 = "Unavailable", "Unavailable"
for service in services:
try:
response = requests.get(service, headers=headers, timeout=0.2)
if response.status_code == 200:
return response.text.strip()
ip = response.text.strip()
if ":" in ip: # IPv6 address
ipv6 = ip
else: # IPv4 address
ipv4 = ip
if ipv4 != "Unavailable" and ipv6 != "Unavailable":
break
except requests.RequestException:
continue
return "Unable to fetch external IP"
return ipv4, ipv6
def display_interface_details(show_physical=False, show_virtual=False, show_all=False, show_external_ip=False):
"""
@ -144,8 +154,9 @@ def display_interface_details(show_physical=False, show_virtual=False, show_all=
- If `-e` is specified, the external IP address is displayed.
"""
if show_external_ip:
external_ip = get_external_ip()
print(f"External IP: {external_ip}")
ipv4, ipv6 = get_external_ips()
print(f"External IPv4: {ipv4}")
print(f"External IPv6: {ipv6}")
print("-" * 50)
interfaces = []