Skip to content

Instantly share code, notes, and snippets.

@stewartadam
Last active November 9, 2022 08:45
Show Gist options
  • Save stewartadam/db9223bb4d50afa94ce9f5250def05e6 to your computer and use it in GitHub Desktop.
Save stewartadam/db9223bb4d50afa94ce9f5250def05e6 to your computer and use it in GitHub Desktop.
Obtain list of active network services on MacOS
# improvement of answer https://apple.stackexchange.com/a/223446/183406
# fixes issue where multiple services may have the same hardware port (e.g. USB Ethernet)
get_interfaces() {
while read -r line; do
sname="$(echo "$line" | sed -E 's|(.*) \(Hardware Port: (.+), Device: (.+)\)|\1|')"
hname="$(echo "$line" | sed -E 's|(.*) \(Hardware Port: (.+), Device: (.+)\)|\2|')"
sdev="$(echo "$line" | sed -E 's|(.*) \(Hardware Port: (.+), Device: (.+)\)|\3|')"
#echo "Current service: $sname, $sdev, $currentservice"
if [ -n "$sdev" ]; then
ifout="$(ifconfig "$sdev" 2>/dev/null)"
echo "$ifout" | grep 'status: active' > /dev/null 2>&1
rc="$?"
if [ "$rc" -eq 0 ]; then
currentservice="$sname"
currentdevice="$sdev"
currentmac=$(echo "$ifout" | awk '/ether/{print $2}')
# may have multiple active devices, so echo it here
echo "$currentservice, $currentdevice, $currentmac"
fi
fi
done <<< "$(networksetup -listnetworkserviceorder | awk 'BEGIN { RS = "\\([0-9]\+\\) " ; FS = "\n" } { print $1, $2 }')"
if [ -z "$currentservice" ]; then
>&2 echo "Could not find current service"
exit 1
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment