Dean_5 0 Newbie Poster

What it says on the tin.

When the system (without logging into X) detects a change in internet accessibility, I'd like to set a hook to execute a script.
EDIT: Every single bloody time... So, exists... is that the preferred method or can anyone recommend something else that's - in their mind - better?

2nd EDIT: I really am asking these questions. It's just that, in the process of writing the posts, I think of a different way to google the question and the answer magically appears.

Dani AI

Generated

Short answer: use the hook mechanism provided by whatever networking stack you actually run. If you run dhcpcd then dhcpcd-run-hooks is a perfectly valid choice for reacting to DHCP events, but note DHCP events are not the same as "internet reachability" — a lease renewal or interface up/down may not catch upstream outages, DNS failures, or transient packet loss. , since you want the hook to fire "every single time" Internet access changes, prefer a reachability-driven solution or a dispatcher that your networking daemon provides.

Common approaches (pick one that matches your stack)

  • dhcpcd hooks — good for DHCP lifecycle events (if you already use dhcpcd).
  • ifupdown scripts (/etc/network/if-up.d, if-down.d) — runs on interface config.
  • NetworkManager dispatcher (/etc/NetworkManager/dispatcher.d) — for systems using NM, headless or not.
  • systemd-networkd + networkd-dispatcher — modern, lightweight, and integrates with systemd.
  • link-level tools (ifplugd) — for physical plug/unplug only.
  • reachability-monitor daemon — independent, reliable way to detect actual Internet up/down and call on-connect/on-disconnect scripts (recommended if you truly need every change).

Minimal, pragmatic example (monitor + trigger)
Create a short monitor that periodically tests a configurable endpoint and calls user scripts only when state changes:

#!/bin/sh
STATEFILE=/run/internet-state
check(){ ping -c1 -W2 1.1.1.1 >/dev/null 2>&1 && echo up || echo down; }
old=$(cat "$STATEFILE" 2>/dev/null || echo unknown)
while true; do
  new=$(check)
  [ "$new" = "$old" ] || { [ "$new" = up ] && /usr/local/bin/internet-up.sh || /usr/local/bin/internet-down.sh; echo "$new" >"$STATEFILE"; old=$new; }
  sleep 5
done

Notes and cautions: make on-connect/down scripts short and nonblocking, use sensible timeouts, test with multiple endpoints (ICMP may be blocked — consider TCP/HTTP checks), and run the monitor under systemd with Restart=always. If you only need to react to DHCP changes, dhcpcd hooks are simplest; for true reachability notifications use the monitor/dispatcher approach.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.