What does “scope” do in ip route and why it is necessary to setup static route in Linux?

8,472

These routes are how you tell the Linux kernel what subnet(s) you're in.

This information isn't stored in a hidden "my current subnet" field when you add an IP address; instead it's always converted to a 'scope link' route with no gateway specified (also called "device route" or "interface route"), and whenever the kernel needs to determine whether some address is directly reachable, it just performs a routing table check.

Normally those routes are added automatically as soon as you configure an IP address – for example, running ip addr add 192.168.1.5/24 assigns the IP address 192.168.1.5 and creates a subnet route for 192.168.1.0/24. So it's not necessary to add these routes in normal usage.

But when you blindly "delete all routes", you also end up deleting these automatically created routes, and the kernel's "is this address in my subnet" checks no longer work. That's why you end up having to re-add the routes manually.

(The kernel needs to perform this check during ip route add because route gateways (nexthops) must be directly reachable on the same L2 connection – they cannot be behind another gateway. That is, the gateway must be in your subnet.

Route scopes are a generic mechanism to express this restriction: the new route's nexthop needs to be reachable through an existing route with a lower scope. In other words, you must go through a local host (link scope) before you can reach a remote host (global scope).)

Share:
8,472

Related videos on Youtube

user762750
Author by

user762750

Updated on September 18, 2022

Comments

  • user762750
    user762750 over 1 year

    If I want to replace default dhcp route rules with static ones, I have to add a rule ip route add scope link dev eth0. Or I will get an error: “Nexthop has a invalid gateway”.

    Here are my questions:
    Q1: What does “scope link” mean in ip route?
    Q2: Why it is necessary to change from dhcp rules to static rules?

    • user1686
      user1686 over 5 years
      What full commands give the error, and what full commands are you using to add the link routes?
    • user762750
      user762750 over 5 years
      @grawity After deleting all rules, I execute “ip route add default 192.168.1.1 proto static dev eth0”
  • user762750
    user762750 over 5 years
    Thank you for solving my doubts, but I have another question: why this “link scope” command is not needed when I configure systemd-networkd with static IP address?
  • user1686
    user1686 over 5 years
    The kernel automatically creates these routes when you add an IP address. So the command is never needed unless you first add an address and then delete all routes.