1

How do I find the network interface that's connected to the Internet?

This machine could typically be connected via {eth0,eth1,usb0,wlan0}. The best I could think of is:

sudo route | grep default | awk '{print $NF}'

Update: My favoured solution is:

 $(for i in `ip r`; do echo $i; done | grep -A 1 dev | tail -n1)
hendry
  • 667
  • 2
  • 10
  • 23
  • 1
    The Internet should be accessed normally via default gateway. You can use the command `sudo route | grep UG | awk '{print $NF}'` – Khaled Nov 26 '11 at 11:42
  • @Khaled, there can be more than one interfaces using gateways(Flag G). So your answer is wrong. – Sachin Divekar Nov 26 '11 at 12:04
  • possible duplicate of [How do i get the default gateway in LINUX given the destination?](http://serverfault.com/questions/47915/how-do-i-get-the-default-gateway-in-linux-given-the-destination) – quanta Nov 26 '11 at 12:25
  • 12:02 hendry: route -n | awk '/^0\.0\.0\.0/{print $NF}' or ip route list 0.0.0.0/0 | sed -n 's/default.*dev \([^[:space:]]\+\)/\1/p' or parsing /proc/net/route on Linux... it seems there's no portable way to do that – hendry Nov 26 '11 at 14:00
  • Thinking of tweaking my question to find the IP of the connected interface too. – hendry Nov 27 '11 at 12:30

2 Answers2

2

i think it will be better to use iproute2 instead old and bad-working route.

ip r | sed -n '/^de/s/.*dev //p'
rush
  • 1,961
  • 2
  • 15
  • 22
  • +1. I agree. Though I have provided answer using `route` command, We should use iproute2 commands wherever possible. – Sachin Divekar Nov 26 '11 at 20:22
  • `x220:~$ ip r | sed -n '/^de/s/.*dev //p' eth0 metric 202` I think the regexp can be improved. Gah, why is it soo difficult to parse? – hendry Nov 27 '11 at 12:22
  • Your solution isn't perfect, I have a "metric 202" suffix. I've added my solution in the question above and accepted your answer, since I've grateful you have showed me `ip r`. :) – hendry Nov 29 '11 at 07:00
  • 1
    nice idea, but awk seems the better tool for that task: `ip r | awk '/^de/{print $NF}'` – ThorstenS Nov 29 '11 at 07:43
1

route -n | awk '$1 ~ /0.0.0.0/ {print $NF}' will give you interface with default gateway which is most probably the interface through which you are accessing internet.

Sachin Divekar
  • 2,445
  • 2
  • 20
  • 23