diff --git a/config/ansible/tasks/global/utils/ipaddr b/config/ansible/tasks/global/utils/ipaddr index 2056350..2faa1a5 100755 --- a/config/ansible/tasks/global/utils/ipaddr +++ b/config/ansible/tasks/global/utils/ipaddr @@ -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 = []