Build a Python Public IP Change Monitor That Alerts You When Your IP Changes
Most home internet connections have a dynamic public IP address: your ISP can change it whenever your router reconnects. That is normal — but a sudden, unexpected change is also one of the earliest signs that something is wrong: a router reboot you did not trigger, an ISP-level change, or in the worst case, someone messing with your connection. A tiny Python monitor that checks your IP every few minutes and alerts you on change turns an invisible event into a notification you actually see.
The Code
import json
import os
import time
import urllib.request
from datetime import datetime
STATE_FILE = os.path.expanduser("~/.ip_monitor_state.json")
CHECK_URLS = [
"https://api.ipify.org",
"https://ifconfig.me/ip",
"https://icanhazip.com",
]
CHECK_EVERY_SECONDS = 300 # 5 minutes
def get_public_ip():
"""Ask a public IP service what our address is. Try backups."""
for url in CHECK_URLS:
try:
req = urllib.request.Request(url, headers={"User-Agent": "ip-monitor/1.0"})
with urllib.request.urlopen(req, timeout=10) as resp:
ip = resp.read().decode().strip()
if ip and ip.count(".") == 3:
return ip
except Exception:
continue
return None
def load_state():
if os.path.exists(STATE_FILE):
with open(STATE_FILE) as f:
return json.load(f)
return {}
def save_state(state):
with open(STATE_FILE, "w") as f:
json.dump(state, f)
def alert(message):
# Swap this for your own alert: Telegram bot, email, webhook.
print(f"[ALERT] {datetime.now():%Y-%m-%d %H:%M:%S} {message}")
def main():
state = load_state()
while True:
ip = get_public_ip()
if ip is None:
print("Could not reach any IP service — check your connection.")
else:
old_ip = state.get("ip")
if old_ip is None:
print(f"First run — current public IP is {ip}. Monitoring started.")
elif ip != old_ip:
alert(f"Public IP changed: {old_ip} -> {ip}")
state["ip"] = ip
state["last_check"] = datetime.now().isoformat()
save_state(state)
time.sleep(CHECK_EVERY_SECONDS)
if __name__ == "__main__":
main()
How It Works
- Three fallback services. The script asks ipify, ifconfig.me and icanhazip what your public IP is, trying the next one if the first fails. No single service is a point of failure.
- Persistent state. The last seen IP is saved to a small JSON file in your home directory, so the monitor remembers across restarts.
- Change detection. Every five minutes it compares the current IP with the saved one. A difference triggers an alert — and the first run just records the baseline without crying wolf.
- Pluggable alerts. The
alert()function currently prints to the console. Replace it with a Telegram bot message, an email, or a webhook to your phone and the monitor becomes genuinely useful.
Run It in the Background
Run it as a background process with nohup python3 ip_monitor.py &, or better, as a systemd user service so it survives reboots:
mkdir -p ~/.config/systemd/user
Create ~/.config/systemd/user/ip-monitor.service with ExecStart=/usr/bin/python3 /home/anony/ip_monitor.py, then run systemctl --user enable --now ip-monitor.
Why This Matters for Security
A public IP change is boring 99% of the time — your router reconnected, your ISP rotated addresses. But the 1% is worth knowing about: a router that reboots on its own can mean a crash, a firmware update, or an attacker. A changed IP also breaks any allow-list you set up on a VPS or a firewall, and breaks remote access until you update it. Knowing the moment it changes means you fix access in minutes instead of discovering it hours later when you need to log in remotely.
Level Up
- Log every change with timestamps to spot patterns — does your IP change every night at 3 a.m.?
- Add a reverse DNS lookup on each new IP to see if it belongs to a different ISP range than usual.
- Combine it with a port scan of your own public IP (only your own) to confirm nothing new is exposed after a change.
You just built a network watchdog in 60 lines. That is the whole point of automation: small scripts watching boring things, so you only get woken up when something actually changes.



Comments
Post a Comment