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)
5
  • 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, 2011 at 11:42
  • @Khaled, there can be more than one interfaces using gateways(Flag G). So your answer is wrong. Nov 26, 2011 at 12:04
  • possible duplicate of How do i get the default gateway in LINUX given the destination?
    – quanta
    Nov 26, 2011 at 12:25
  • 12:02 <biz> 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, 2011 at 14:00
  • Thinking of tweaking my question to find the IP of the connected interface too.
    – hendry
    Nov 27, 2011 at 12:30

2 Answers 2

2

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

ip r | sed -n '/^de/s/.*dev //p'
4
  • +1. I agree. Though I have provided answer using route command, We should use iproute2 commands wherever possible. Nov 26, 2011 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, 2011 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, 2011 at 7:00
  • 1
    nice idea, but awk seems the better tool for that task: ip r | awk '/^de/{print $NF}'
    – ThorstenS
    Nov 29, 2011 at 7: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.

You must log in to answer this question.

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