Apple - How to find the currently connected network service from the command line?

Put it all together, I wrote a script to accomplish this task:

#!/bin/bash

while read -r line; do
    sname=$(echo "$line" | awk -F  "(, )|(: )|[)]" '{print $2}')
    sdev=$(echo "$line" | awk -F  "(, )|(: )|[)]" '{print $4}')
    #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 | grep 'Hardware Port')"

if [ -z "$currentservice" ]; then
    >&2 echo "Could not find current service"
    exit 1
fi

The script first get a service list from networksetup command, then check if each service is in active status from ifconfig.

Name the script to networkservice.sh for example, then execute it to get the current network service you are on.

$ bash networkservice.sh
USB 10/100/1000 LAN, en4, 00:e0:4a:6b:4d:0c
Wi-Fi, en0, 8c:85:90:a0:4b:ec

Simply issue

    ifconfig

List all network interfaces and their status.


I won't pretend to have the answer to this question sorted, but this but this maybe helpful.

You can ask how it currently will route packets to something:

$ route get example.com | grep interface
interface: en8

And then you can ask what "Network Service" is managing that interface:

$ networksetup -listnetworkserviceorder | grep en8
(Hardware Port: Broadcom NetXtreme Gigabit Ethernet Controller, Device: en8)

But honestly, I doubt that a "Network Services" is one to one with a hardware port. And some interfaces, tun0 for example, do not have a "Network Service". Well at least sometimes they don't.