Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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)
share|improve this question
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? –  quanta Nov 26 '11 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 '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 Answers 2

up vote 2 down vote accepted

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

ip r | sed -n '/^de/s/.*dev //p'
share|improve this answer
    
+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 7:00
    
nice idea, but awk seems the better tool for that task: ip r | awk '/^de/{print $NF}' –  ThorstenS Nov 29 '11 at 7:43

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.