Detect active ethernet and wifi and take action

j120p
New Contributor

We are trying to write a script to output all the active wifi and ethernet connections, if any, and turn off the wifi if there is an active ethernet connection. This is not working at all, because ifconfig is not returning the names of the connections (which may or may not be ethernet). networksetup -listallhardwareports is better as it displays the name of the "hardware port" but doesn't list the status. This seems promising but we haven't been able to use it in a script https://developer.apple.com/documentation/systemconfiguration/1517371-scnetworkinterfacegetinterface...

 

#!/bin/bash

# Define the names of the interfaces
WI_FI_INTERFACE="Wi-Fi"
ETHERNET_INTERFACE="Ethernet"

# Check if the Ethernet interface is active
ethernet_status=$(ifconfig "$ETHERNET_INTERFACE" | grep "status: active")

if [ -n "$ethernet_status" ]; then
echo "Ethernet is active. Turning off Wi-Fi..."
networksetup -setairportpower "$WI_FI_INTERFACE" off
else
echo "Ethernet is not active. Turning on Wi-Fi..."
networksetup -setairportpower "$WI_FI_INTERFACE" on
fi

0 REPLIES 0