简体   繁体   English

Mac OS X中的网络状态更改通知

[英]Network status change notification in mac os x

In Mac Os X how my application get informed when the status of network connection changes? 在Mac Os X中,当网络连接状态更改时,如何通知我的应用程序? I tried using SCNetworkConnectionGetStatus from SCNetworkConnection Reference. 我尝试使用《 SCNetworkConnection参考》中的SCNetworkConnectionGetStatus。 But it has to be called continuously. 但是必须不断调用它。 I need an API which will will inform me as soon as network status chages. 我需要一个API,它将在网络状态发生变化时立即通知我。

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. 一旦有了这个脚本,我就将其放入基本的while循环和voila中-网络连接更改监视。

#!/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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM