Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the OS know which network interface to use for the internet?

I have a PC with two network interfaces: eth0 and eth1.

eth0 - Has an ip of 192.168.11.X/24.

eth1 - Has an ip of 192.168.130.X/24. eth1 has internet connectivity.

How does my OS know which interface to use when I try connecting to the internet? Does it iterate over all default gateways? Does it have any cache of what each interface provides? Is there any difference in the behaivior between Windows and Linux?

like image 340
Uri H Avatar asked Aug 24 '12 12:08

Uri H


2 Answers

I'm going to answer for the Linux side of the house (at least for Debian-based systems, such as Ubuntu, since it's more common for users at this point):

Type the following into a command line:

route -n

You should see your "routing table" appear, with something like the following:

Destination    Gateway          Genmask         ...    Iface
0.0.0.0        192.168.11.254   0.0.0.0         ...    eth0
169.254.0.0    0.0.0.0          255.255.0.0     ...    eth0
192.168.11.0   0.0.0.0          255.255.255.0   ...    eth0
192.168.130.0  0.0.0.0          255.255.255.0   ...    eth1

I omitted a couple columns, but basically, the line that says "0.0.0.0" under "Destination" is the line that determines where your default route is. In other words, where all of the traffic goes that isn't destined for any of the other subnets in the other lines (google.com, facebook.com, whatever).

If it's not right (such as in the above table, where "eth1" is the card you want with Internet access), you should change the default route:

sudo route del default
sudo route add default gw 192.168.130.254 netmask 255.255.255.0

That will fix it for now. To make it permanent, edit your interfaces file:

sudo gedit /etc/network/interfaces

Edit it to look something like the following (change as necessary to your specific situation):

auto eth0
iface eth0 inet dhcp
up route del default

auto eth1
iface eth1 inet dhcp
up route add default gw 192.168.130.254 netmask 255.255.255.0

Then restart networking to see if that did the trick:

sudo /etc/init.d/networking restart
like image 187
JoeLinux Avatar answered Sep 28 '22 12:09

JoeLinux


The feature you're asking about is a routing table, a list of destinations known to the host.

When the OS needs to forward a packet it checks this list and chooses the most appropriate one (from specific destinations to general ones). For example:

192.0.2.0/28    - 192.0.2.1 via eth1
198.51.100.0/27 - 198.51.100.1 via eth0
0.0.0.0/0       - 203.0.113.1 via eth0

Note the last destination: it will match any IPv4 address.

like image 35
cnicutar Avatar answered Sep 28 '22 10:09

cnicutar