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

Uri H picture Uri H · Aug 24, 2012 · Viewed 9.9k times · Source

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?

Answer

JoeLinux picture JoeLinux · Aug 24, 2012

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