Changing the default route in Linux

How many times did you plug in your Ethernet cable into your Linux machine and found out that you couldn’t access the network from the wireless? Or the other way around, connecting to the wireless and not being able use your cabled connection? It happened to me a lot. In most cases they were the same network, but the wireless was terrible. 


Regardless of the reason, I wanted to have a fast way to switch between using my wired and wireless connection without actually disconnecting. The way to do it is to change the default gateway in the machines routing table.

To find out your default gateway, use the route -n command. You should get a output like the one in the screenshot. In my case, my default gateway for connecting to the internet (see Destination is belonging to the eth1 interface. To change this to wlan0 , you need to delete the default gateway and add a different default gateway, by using the following commands :

route del default
route add default gw wlan0

Change the IP with the one appropriate for your environment.

After realizing that I needed to do this more often, especially when testing stuff, I wanted a faster way to do this. Even though there are 2 commands, it’s still annoying to type them repeatedly. To do it faster, I created a simple bash script that will check the current default gateway and will switch with the gateway from the other interface. You can download the script from the Resources page. Be sure to modify the “IFACE” variables with the ones from your machine. In order for the script to be executed as a normal command copy it to /usr/sbin/ and make it executable, using the commands from below. Change “COMMANDNAME” with whatever you want to use when running the command (e.g. changedefroute)

cp /usr/sbin/COMMANDNAME

chmod +x /usr/sbin/COMMANDNAME