I am currently working on how to switch network interface in Linux environment. And i am experimenting on switching network interface by switching default gateway, for example switch to wlan0 when eth0 is the dominant connection. What I typically do is:

route delete default gw eth0
route add default gw wlan0

I want to automate this process into script, but I haven't been able to find a reliable way to get wlan0's router address. Since it is not the dominating connection, netstat -rn and ip route do not give gateway address, and arp -n is not reliable to help me discriminate which IP is router's.

Is there a way to switch interface only be interface name, just like what would happen when I unplug ethernet? Or is there an alternative way to do the switch, or find router's address?

1 Answer 1


Unless somebody else comes with an unknown tool, this can't be done in a elegant way that we both want to.

First answer, there is no way to switch the default gateway just referencing by name. The only and right way is using route command, like you're doing.

Second, you can find the router just by pinging any host with a TTL's package of 1. Use traceroute and filter the first hop.

Use -t parameter of ping to set the time to live:

$ ping -t 1

The IP above should be your router's IP. And traceroute is quite simple:

$ traceroute

What you're doing is called interface fail over and each sysadmin do it using their own Bash scripts.

  • Actually the route command has been deprecated for some time now, you should use ip with appropriate options for such things. You can do ip route replace default via dev wlan0 instead of the two route commands in the question. You can leave out the gateway, but then the system will do an ARP for every remote IP address it wants to reach, and the gateway system will need to proxy arp those; not recommended, even if it does work.
    – wurtel
    Apr 2, 2015 at 6:58
  • @wurtel So you are saying I can do it with: ip route replace default via dev wlan0 ? What's the syntax for 'leave out gateway'? Apr 2, 2015 at 16:02
  • @willian-paixao Can you show me 'ping any host with TTL package of 1' and how to traceroute that? Apr 2, 2015 at 16:05
  • @LingyuanHe, I just edited my previous answer. Anything, let me know. Apr 2, 2015 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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