In embedded development and network operations, when devices connect to different networks through multiple network interfaces (such as Ethernet, Wi-Fi, and 4G modules), how can we ensure that data packets are transmitted through the “optimal path”? The core of this is the metric. This article will delve into this mechanism and introduce simple operational commands.
1. Why is it necessary to set network interface priority?
Common scenarios of multiple network interfaces in embedded devices or servers include:
1. Multiple Network Cards: Connecting via wired (eth0) and wireless (wlan0) dual network cards to ensure high network availability.
2. Multi-Carrier Networks: Simultaneously accessing telecom and Unicom networks, switching exit paths as needed.
3. Embedded Device Networking: For example, industrial gateways communicating through Ethernet, 4G, and Wi-Fi in multi-mode.
The core issue: When the default routes (0.0.0.0/0) of multiple interfaces conflict, how does the system choose the “optimal” path?
The answer: By setting the priority through metric.
2. What is a metric?
A metric is a numerical value in the routing table that represents the “cost” of a path, used to measure the priority of network interfaces.
The smaller the metric value, the higher the priority: the system will choose the route with the smallest metric.
If the metrics are the same: The Linux kernel will choose the path based on the interface index number (if index) or the order of the routing table.
Example of a routing table
$ ip route show default via 192.168.1.1 dev eth0 metric 100 default via 192.168.2.1 dev wlan0 metric 200
Network packets will prioritize the eth0 interface: because its metric is 100, which is less than wlan0’s 200.
3. Viewing and Setting Metrics
1. View current metric configuration
# View the <strong>metric</strong> values in the routing table
route -n
# Or use the more modern ip command
ip route show
2. Modify metric
You can temporarily modify it using the ip route command or the route command.
# Add a default route for eth0, metric=100
sudo ip route add default via 192.168.1.1 dev eth0 metric 100
# Add a default route for wlan0, metric=200 (lower priority)
sudo ip route add default via 192.168.2.1 dev wlan0 metric 200
# Add a default route for eth0, metric=100
route add default gw 192.168.1.1 dev eth0 metic 100
# Add a default route for wlan0, metric=200 (lower priority)
route add default gw 192.168.2.1 dev wlan0 metric 200
You can also permanently modify it through startup scripts or configuration files of other tools.
4. Considerations
The risk of identical metrics: This may lead to interface conflicts (e.g., eth0 and wlan0 competing for the default route).