13

I want to detect when the network changes from ethernet to wifi (or wifi to ethernet). I want to have an observer to notify me about this change.

reachability isn't good enough - it's always returns ReachableViaWiFi for both cases.

P.S - There were some questions regarding this topic before, but none of them has a good answer, and since those questions are more than a year old, maybe someone already find out how to do it

2
  • 1
    What if you are connected to both?
    – Sulthan
    Feb 7, 2017 at 13:39
  • 1
    You can consider CoreWLAN framework if you are programming on macOS
    – frank
    Feb 27, 2018 at 11:04

3 Answers 3

11
+50

You can access system network preferences through SystemConfiguration module, which helps you get touch to system preferences store currently resides in the default location /Library/Preferences/SystemConfiguration/preferences.plist.

Since then, you can receive notifications from SCDynamicStore by SCDynamicStoreNotifyValue(_:_:) or retrieve value by SCDynamicStoreCopyValue(_:_:).

Example for directly lookup current primary network service:

var store = SCDynamicStoreCreate(nil, "Example" as CFString, nil, nil)
var global = SCDynamicStoreCopyValue(store, "State:/Network/Global/IPv4" as CFString)!

var pref = SCPreferencesCreate(nil, "Example" as CFString, nil)
var service = SCNetworkServiceCopy(pref!, global["PrimaryService"] as! CFString)
var interface = SCNetworkServiceGetInterface(service!)

SCNetworkInterfaceGetInterfaceType(interface!) /// Optional("IEEE80211") -> Wi-Fi

Or create dynamic store with callback and set notification keys to receive notifications as every time primary network service changes the notification is going to fire:

var callback: SCDynamicStoreCallBack = { (store, _, _) in
  /* Do anything you want */
}
var store = SCDynamicStoreCreate(nil, "Example" as CFString, callback, nil)
SCDynamicStoreSetNotificationKeys(store!, ["State:/Network/Global/IPv4"] as CFArray, nil)
2
  • 1
    Thanks, but I want to include the wifi/ethernet detection at my app, so when the user runs the app, the app will get notifications about the interface change and do some action. Feb 9, 2017 at 15:43
  • @Roee84 I have updated the answer to include notification examples :)
    – legendecas
    Feb 10, 2017 at 12:11
4

Please note that a Mac can have multiple active interfaces at the same time and some of these may be Ethernet and some of them may be WiFi. Even if you just monitor the primary interfaces, take note that a Mac can have multiple primary interfaces, one per protocol (e.g. the primary interface for IPv4 may not be the primary one for IPv6).

For demonstration purposes, I will assume that you want to monitor the primary IPv4 interface. Here is code that you can just copy & paste to a swift file and directly run from command line (e.g. swift someFile.swift):

import Foundation
import SystemConfiguration

let DynamicStore = SCDynamicStoreCreate(
    nil, "Name of your App" as CFString,
    { ( _, _, _ ) in PrimaryIPv4InterfaceChanged() }, nil)!

func PrimaryIPv4InterfaceChanged ( ) {
    guard let ipv4State = SCDynamicStoreCopyValue(DynamicStore,
        "State:/Network/Global/IPv4" as CFString) as? [CFString: Any]
        else {
            print("No primary IPv4 interface available")
            return
        }

    guard let primaryServiceID =
        ipv4State[kSCDynamicStorePropNetPrimaryService]
        else { return }

    let interfaceStateName =
        "Setup:/Network/Service/\(primaryServiceID)/Interface"
        as CFString

    guard let primaryServiceState = SCDynamicStoreCopyValue(
        DynamicStore, interfaceStateName) as? [CFString: Any]
        else { return }

    guard let hardwareType =
        primaryServiceState[kSCPropNetInterfaceHardware]
        else { return }

    switch hardwareType as! CFString {
        case kSCEntNetAirPort:
            print("Primary IPv4 interface is now WiFi")

        case kSCEntNetEthernet:
            print("Primary IPv4 interface is now Ethernet")

        default:
            print("Primary IPv4 interface is something else")
    }
}

SCDynamicStoreSetNotificationKeys(
    DynamicStore, [ "State:/Network/Global/IPv4" ] as CFArray, nil)

SCDynamicStoreSetDispatchQueue(DynamicStore, DispatchQueue.main)

dispatchMain()

While it is running, try switching your primary IPv4 interface, pull network cables, turn off WiFi, etc. and watch the output. You can stop it by hitting CTRL+C on your keyboard.

1

You could run a little bash script under launchd that monitors the interfaces you are interested in and launches something when they change.

Say your wired connection is en0, you could run:

./netmon en0

Save this script as netmon and make it executable with chmod +x netmon

#!/bin/bash
interface=$1

# Get current status of interface whose name is passed, e.g. en0
status(){
   ifconfig $1 | awk '/status:/{print $2}'
}

# Monitor interface until killed, echoing changes in status
previous=$(status $interface)
while :; do
   current=$(status $interface)
   if [ $current != $previous ]; then
      echo $interface now $current
      previous=$current
   fi 
   sleep 5
done
2
  • Thanks, but I want to include the wifi/ethernet detection at my app, so when the user runs the app, the app will get notifications about the interface change and do some action. Feb 9, 2017 at 15:43
  • So start a new thread that runs my script and read its output and act accordingly. Feb 9, 2017 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.