2

In Mac Os X how my application get informed when the status of network connection changes? I tried using SCNetworkConnectionGetStatus from SCNetworkConnection Reference. But it has to be called continuously. I need an API which will will inform me as soon as network status chages.

Anup
  • 134
  • 1
  • 2
  • 8
  • exact duplicate of [Asynchronous network interface status check](http://stackoverflow.com/questions/7793657/asynchronous-network-interface-status-check) – Mahmoud Al-Qudsi Feb 20 '12 at 07:11
  • I added runloop and callback function to get the continuous status.I used the example simpledial from macosx samples. My program is running but not giving the expected results. I think there is problem in SCNetworkConnectionCopyUserPreferences funtion. Can somebody provide me more information on this function? – Anup Mar 05 '12 at 07:00
  • @MahmoudAl-Qudsi 's comment above should eventually lead you to [this accepted answer to a similar question](http://stackoverflow.com/a/3597085/2264149). Have you taken a look? It uses the SystemConfiguration framework and a special version of the Reachability class. – Valdimar May 17 '16 at 00:06

1 Answers1

1

This is what I ended up using. Once I had this script I just put it into a basic while loop and voila -- network connectivity change monitoring.

#!/bin/bash
set -o pipefail

configured_ip_addresses="$((ifconfig | \
  grep -iEo '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | \
  grep -vi '127.0.0.1' | tr '\n' ' ') || echo NONE_CONFIGURED)"
externally_visible_ip_address="$(curl -m 1 ipinfo.io/ip 2>/dev/null || echo NO_CONNECTIVITY)"
computed_state="Actual:  $externally_visible_ip_address, Configured: $configured_ip_addresses"

statefile="/tmp/net-watcher.state"
if [ -f $statefile ]; then
  echo "$computed_state" > "${statefile}-new"
  new_chksum="$(md5 "${statefile}-new" | awk '{print $NF}')"
  existing_chksum="$(md5 "${statefile}" | awk '{print $NF}')"
  if [[ "${new_chksum}" != "${existing_chksum}" ]]; then
    mv "${statefile}-new" "${statefile}"
    osascript -e "display notification \"$(cat $statefile)\" with title \"ALERT: Network Changed\""
  else
    rm "${statefile}-new"
  fi
else
  echo "$computed_state" > $statefile
fi
bitcycle
  • 7,632
  • 16
  • 70
  • 121