Python function: Check My IP

For some scripts, I need to check if I'm using my own IP or a different one (VPN).

Here is the function I use:

import requests
import os

from dotenv import load_dotenv
load_dotenv()
MY_IP = os.getenv("MY_IP")

def check_my_ip():
    global MY_IP
    try:
        response = requests.get('https://api.ipify.org?format=json')
        response.raise_for_status()
        data = response.json()
        ip = data['ip']
        if ip != MY_IP:
            print(f"\n✅ Using a different IP: {ip} != {MY_IP}")
            return True
        else:
            print(f"\n❌ EXPOSED: Using my IP: {ip} == {MY_IP}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"\n❌ IP Error: {e}")
        return False

Added to my my_utils.py library my-utils

This gets used then in my scripts as follows, if script needs to run on a protected IP address:

from my_utils import check_my_ip

if check_my_ip():
    # do something

links

social