I have several scripts that require determining which network I'm connected to (with my Linux laptop), for example mounting a local NAS or (dis/)enabling a specific service. An added complexity is that some (most) networks should still be correctly identified when connected through a different SSID or network interface (cabled / WiFi). Also I can't rely on a specific host being available.

My current script is parsing the routing table to find the default gateway and associated MAC address, using the IPv4 gateway as default and the IPv6 gateway as fallback:


ROUTER=$(ip -4 route list | grep "default" | head -n 1 | cut -f 3 -d " ")
# echo "ROUTER=${ROUTER}" >&2
if [ "${ROUTER}" != "" ]; then
    MAC=$(ip neigh | grep -E "^${ROUTER} " | cut -f 5 -d " ")
    # echo "MAC=${MAC}" >&2
    if [ ${MAC} != "" ]; then
        echo "${MAC}"
        exit 0

ROUTER6=$(ip neigh | grep -R "^fe80.* router " | head -n 1 | cut -f 1 -d " ")
# echo "ROUTER6=${ROUTER6}" >&2
if [ "${ROUTER6}" != "" ]; then
    MAC6=$(ip neigh | grep -E "^fe80.* router " | head -n 1 | cut -f 5 -d " ")
    # echo "MAC6=${MAC6}" >&2
    if [ "${MAC6}" != "" ]; then
        echo "${MAC6}"
        exit 0

exit 1

Which works ok so far, but may be a little fragile with all the field parsing and reliance on the gateway MAC.

Is there a better way to get a reliable network ID that can identify a network regardless of connection method?

  • You could parse the output of tracepath -n tracepath is part of the iputils package. It will list all the IPs between you and Google.
    – waltinator
    Dec 17, 2020 at 19:57

1 Answer 1


There is no reliable network identifier, the ip address was supposed to start with the network id, but in private networking this is not unique, unless you use a network that is very random you can detect your own network. ipv6 removes the need for private networking, so if you have a globally unique prefix you could have used that, but yours depends on local fe80. You can use 802.X to do a similar authentication as WIFI so that you authenticate to your known network and trigger scripts from there.

You can slightly optimize by listing just the default routes, so you don't have to grep, but you could have multiple default gateways ip -4 route list default

You could depend on mdns for service discovery or another form of beacon. There is a host identity protocol that could serve as a beacon, but since you don't want to rely on a single host, so personally I would regularly collect the arp table (e.g. output of arp -an) or straight from /proc/net/arp and calculate a likelyhood of being connected to a certain network.

Maybe you're just better off sticking to the script you've got.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .