How to find out which interface am I using for connecting to the internet?

You can use route to find your default route:

$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.1.0     *               255.255.255.0   U     1      0        0 eth0
link-local      *               255.255.0.0     U     1000   0        0 eth0
default         192.168.1.1     0.0.0.0         UG    0      0        0 eth0

The Iface column in the line with destination default tells you which interface is used.


My version which is basically based on this and this:

route | grep '^default' | grep -o '[^ ]*$'

And this, experimentally, for macOS:

route -n get default | grep 'interface:' | grep -o '[^ ]*$'

On GNU/Linux systems:

#!/bin/sh

# host we want to "reach"
host=google.com

# get the ip of that host (works with dns and /etc/hosts. In case we get  
# multiple IP addresses, we just want one of them
host_ip=$(getent ahosts "$host" | awk '{print $1; exit}')

# only list the interface used to reach a specific host/IP. We only want the part
# between dev and src (use grep for that)
ip route get "$host_ip" | grep -Po '(?<=(dev )).*(?= src| proto)'

Tags:

Linux

Routing