How can I get public IP address in python programetically. I don't want to hit any 3rd party service url to get the IP

54 Views Asked by At

I want the public IP address for specific IP allowed for my project preference . But I don't want to use any 3rd party service url to get the

IP

. I am using python and fastapi

I can't find anything without 3rd party or paid services

1

There are 1 best solutions below

1
BokiX On

If you are trying to get your routers public (external) IP address then this code should work:

import requests

try:
    public_ip = requests.get('https://api.ipify.org').text
    print(f"Public IP Address: {public_ip}")
except requests.RequestException as e:
    print(f"Error retrieving public IP address: {e}")