Run script every time the system's default gateway changes?

You can monitor files like the following for changes and act accordingly:

  • /private/var/run/resolv.conf

  • /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist

  • /Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist

You can use a Launch Agent with a WatchPaths key, however, see the note regarding its use in the manual page for launchd.plist. I will say that in spite of the note, I have not had issues with a WatchPaths key in my Launch Agents that I currently use. YMMV

If you are going to use Launch Agents and Launch Daemons, I highly recommend you read the manual pages for launchctl, launchd.plist and launchd.

You can read the manual page for command in Terminal by typing man command, then press enter, or for easier reading, just type command and then right-click on it and select: Open man Page

Or use a third-party application like EventScripts.

It can trigger an AppleScript script or a shell script with events like:

  • Internet became available
  • Internet became unavailable
  • External IP address changed
  • Wireless network changed

And many more types of events.

Have a look at EventScripts, it's $5.99 at the US App Store, but a free demo is downloadable from the developers website.

Note: I am not affiliated with the developer of EventScripts, just a satisfied user of the product.