How to get external IPv4 address in Python
Also see:How to get external IPv6 address in Python
You can use the free IPify service together with requests to get your current IPv4 address:
#!/usr/bin/env python3
import requests
def get_current_ipv4():
"""Get the current external IPv4 address or return None if no connection to the IPify service is possible"""
try:
return requests.get("https://api4.ipify.org", timeout=5).text
except requests.exceptions.ConnectionError as ex:
return None
# Usage example
print(get_current_ipv4()) # Prints e.g. 95.216.138.188