[OpenWrt Wiki] docs:guide-user:network:routes_configuration

# add a route without consistency check for gateway reachability

ip route add ${address}/${mask} dev ${interface name} onlink

Example: ip route add 192.0.2.128/25 via 203.0.113.1 dev eth0 onlink

The onlink keyword disables the kernel’s gateway consistency checks and allows adding routes via gateways that look unreachable.
Useful in tunnel configurations and container/virtualization networking with multiple networks on the same link using a single gateway.

# add an address to an interface

ip address add ${address}/${mask} dev ${interface name}


Examples:

ip address add 192.0.2.10/27 dev eth0

ip address add 2001:db8:1::/48 dev tun10

You can add as many addresses as you want.

If you add more than one address, your machine will accept packets for all of them. The first address you add becomes a “primary address”.
The primary address of an interface it’s used as the source address for outgoing packets by default.
All additional addresses you set will become secondary addresses.

# add an address with a human-readable description

ip address add ${address}/${mask} dev ${interface name} label ${interface name}:${description} 

Examples:

ip address add 192.0.2.1/24 dev eth0 label eth0:WANaddress

The label must start with the interface name followed by a colon due to some backward compatibility issues, otherwise you’ll get an error.
Keep the label shorter than sixteen characters, or else you’ll get this error: RTNETLINK answers: Numerical result out of range.

# assign a network interface to a namespace

ip link set dev ${interface name} netns ${namespace name}

ip link set dev ${interface name} netns ${pid}

Example: ip link set dev eth0.100 netns foo.

Note: once you assign an interface to a namespace, it disappears from the default namespace, and you will have to perform all operations with it via ip netns exec ${netspace name},
like ip netns exec ${netspace name} ip link set dev dummy0 down.

Moreover, when you move an interface to another namespace, it loses all existing configuration such as IP addresses configured on it and goes to the DOWN state.
You’ll need to bring it back up and reconfigure it.

If you specify a PID instead of a namespace name, the interface gets assigned to the primary namespace of the process with that PID.
This way you can reassign an interface back to the default namespace with e.g., ip netns exec ${namespace name} ip link set dev ${intf} netns 1
(since init or another process with PID 1 is pretty much guaranteed to be in default namespace).

# bind an interface to a vrf

ip link set ${interface} master ${vrf}

Example: ip link set eth0 master foo.

All connected routes associated with the interface will be moved to the VRF table.
For example, if eth0 has address 192.0.2.1/24, and a VRF instance foo uses table 100, then the route to 192.0.2.0/24 will disappear from the main table and re-appear in table 100.

# change link mtu

ip link set dev ${interface name} mtu ${MTU value}


Examples: ip link set dev tun0 mtu 1480

MTU stands for “Maximum Transmission Unit”, the maximum size of a frame an interface can transmit at once.

Apart from reducing fragmentation in tunnels, this is also used to increase the performance of gigabit ethernet links
that support so-called “jumbo frames” (frames up to 9000 bytes large).
If all your equipment supports gigabit ethernet, you may want to do something like ip link set dev eth0 mtu 9000.


Note that you may need to configure it on your L2 switches too, some of them have jumbo frames disabled by default.

# change or replace a route

For modifying routes, there are ip route change and ip route replace commands.
The difference between them is that the change command will produce an error if you try to change a route that doesn’t exist.
The replace command will create a route if it doesn’t exist already.

Examples:

ip route change 192.168.2.0/24 via 10.0.0.1

ip route replace 192.0.2.1/27 dev tun0

# connect one namespace to another


This can be done by creating a pair of veth links and assigning them to different namespaces.

Suppose you want to connect a namespace named “foo” to the default namespace.
First, create a pair of veth devices: ip link add name veth1 type veth peer name veth2.

Move veth2 to namespace foo: ip link set dev veth2 netns foo.

Bring veth2 and add an address in “foo” namespace:

ip netns exec foo ip link set dev veth2 up

ip netns exec foo ip address add 10.1.1.1/24 dev veth2


Add an address to veth1, which stays in the default namespace: ip address add 10.1.1.2/24 dev veth1.

Now you can ping 10.1.1.1, which is in the foo namespace, and set up routes to subnets configured in other interfaces of that namespace.

If you want switching instead of routing, you can bridge those veth interfaces with other interfaces in corresponding namespaces.
The same technique can be used for connecting namespaces to physical networks.

# connected routes


Some routes appear in the system without explicit configuration (“against your will”).

Once you assign an address to an interface, the system calculates its network address and creates a route to that network (this is why the subnet mask is required).
Such routes are called connected routes.

For example, if you assign 203.0.113.25/24 to eth0, a connected route to 203.0.113.0/24 network will be created, and the system will know that hosts from that network can be reached directly.

When an interface goes down, connected routes associated with it are removed. This is used for inaccessible gateway detection, so routes through gateways that went inaccessible are removed.
The same mechanism prevents you from creating routes through inaccessible gateways.

# create a bonding interface

ip link add name ${name} type bond

Examples: ip link add name bond1 type bond

Note: This is not enough to configure bonding (link aggregation) in any meaningful way. You need to set up bonding parameters according to your situation.
This is far beyond the cheat sheet scope, so consult the documentation.


Bonding interface members are added and removed exactly like bridge ports, with master and nomaster commands.

# create a bridge interface

ip link add name ${bridge name} type bridge

Examples: ip link add name br0 type bridge

Bridge interfaces are virtual Ethernet switches.
You can use them to turn a Linux box into a slow L2 switch, or to enable communication between virtual machines on a hypervisor host.
Note that turning a Linux box into a physical switch isn’t a completely absurd idea, since unlike dumb hardware switches, it
can work as a transparent firewall.

You can assign an IP address to a bridge and, it will be visible from all bridge ports.


If bridge creation fails, check if the bridge module is loaded.

# create a dummy interface

ip link add name ${dummy interface name} type dummy

Examples: ip link add name dummy0 type dummy

In Linux, for some strange historical reasons, there’s only one loopback interface.
Dummy interfaces are like loopbacks, but there can be many of them.

They can be used for communication inside a single host.
A loopback or a dummy interface is also a good place to assign a management address
on a router with multiple physical interfaces.

# create a gre tunnel

ip tunnel add ${interface name} mode gre local ${local endpoint address} remote ${remote endpoint address}


Examples:

ip tunnel add tun6 mode gre local 192.0.2.1 remote 203.0.113.3

ip link set dev tun6 up

ip address add 192.168.0.1/30 dev tun6

ip address add 2001:db8:1::1/64 dev tun6

# create a pair of virtual ethernet devices

Virtual ethernet (veth) devices always come in pairs and work as a bidirectional pipe: whatever comes into one of them comes out of the other.
They are used in conjunction with system partitioning features such as network namespaces and containers (OpenVZ or LXC) for connecting one partition to another.

ip link add name ${first device name} type veth peer name ${second device name}

Examples: ip link add name veth-host type veth peer name veth-guest

Note: depending on the kernel version, those devices may be created in either down or up state.
In recent versions (tested in 5.10) they are down. It’s better to assume that they are down and always use
ip link set ${intf} up on them.

# create a point-to-multipoint gre tunnel

ip tunnel add ${interface name} mode gre local ${local endpoint address} key ${key value}


Examples:

ip tunnel add tun8 mode gre local 192.0.2.1 key 1234

ip link set dev tun8 up

ip address add 10.0.0.1/27 dev tun8

Note the absence of ${remote endpoint address}. This is the same as “mode gre multipoint” in Cisco IOS.

In the absence of a remote endpoint address, the key is the only way to identify the tunnel traffic, so ${key value} is required.

Since there is no explicit remote endpoint address, it is obviously not enough to just create a tunnel. Your system needs to know where the other endpoints are.
In real life, NHRP (Next Hop Resolution Protocol) is used for it.


For testing, you can add peers manually (given remote endpoint uses 203.0.113.6 address on its physical interface and 10.0.0.2 on the tunnel):

ip neighbor add 10.0.0.2 lladdr 203.0.113.6 dev tun8

You will have to do it on the remote endpoint as well:

ip neighbor add 10.0.0.1 lladdr 192.0.2.1 dev tun8

# create a policy route

ip route add ${route options} table ${table id or name}

Examples:

ip route add 192.0.2.0/27 via 203.0.113.1 table 10

ip route add 0.0.0.0/0 via 192.168.0.1 table ISP2

ip route add 2001:db8::/48 dev eth1 table 100

Note: You can use any route options described in the route management section for policy routes too,
the only difference is the table ${table id/name} part at the end.


Numeric table identifiers and names can be used interchangeably. To create your own symbolic names, edit the /etc/iproute2/rt_tables config file.

delete, change, replace, and all other route actions work with any table too.

ip route … table main or ip route … table 254 have the exact same effect as commands without a table part.

# create a qinq interface (vlan stacking)

ip link add name ${service interface} link ${physical interface} type vlan proto 802.1ad id ${service tag}

ip link add name ${client interface} link ${service interface} type vlan proto 802.1q id ${client tag}

Example:

ip link add name eth0.100 link eth0 type vlan proto 802.1ad id 100 # Create a service tag interface

ip link add name eth0.100.200 link eth0.100 type vlan proto 802.1q id 200 # Create a client tag interface

VLAN stacking (aka 802.1ad QinQ) is a way to transmit VLAN tagged traffic over another VLAN.
The common use case for it is like this: suppose you are a service provider and you have a customer who wants to use your network infrastructure
to connect parts of their network to each other.

:/>  Архивируем WinRAR’ом, создаем пароль, саморазархивирующийся архив, усиливаем сжатие, разбиваем на тома/архивы и не только | Белые окошки

They use multiple VLANs in their network, so an ordinary rented VLAN is not an option.
With QinQ you can add a second tag to the customer traffic when it enters your network and remove that tag when it exits,
so there are no conflicts, and you don’t need to waste VLAN numbers.

The service tag is a VLAN tag the provider uses to carry client traffic through their network.
The client tag is a tag set by the customer.

Note that link MTU for the client VLAN interface is not adjusted automatically; you need to take care of it yourself
and either decrease the client interface MTU by at least 4 bytes or increase the parent MTU accordingly.


Standards-compliant QinQ is available since Linux 3.10.

# create a rule to match a firewall mark value

ip rule add fwmark ${mark} ${action}

Examples: ip rule add fwmark 0x11 lookup 100.

Make sure to set the mark in a firewall chain that is processed before the routing decision, else your PBR rules that use that mark will have no effect.
You can find an excellent netfilter flowchart in Phil Hagen’s blog.
For forwarded traffic, mangle FORWARD should be a good place, e.g. iptables -t mangle -I FORWARD -s 192.0.2.1 -j MARK –set-mark 0x11.

# create a vlan interface

ip link add name ${VLAN interface name} link ${parent interface name} type vlan id ${tag}

Examples: ip link add name eth0.110 link eth0 type vlan id 110

The only type of VLAN supported by Linux is IEEE 802.1q VLAN; legacy implementations like ISL are not supported.


You can use any name for a VLAN interface. eth0.110 is a traditional format, but it’s not required.

Any Ethernet-like device can be a parent for a VLAN interface: bridge, bonding, L2 tunnels (GRETAP, L2TPv3…).

# create an ip6ip6 tunnel

ip -6 tunnel add ${interface name} mode ip6ip6 local ${local endpoint address} remote ${remote endpoint address}

Examples:

ip -6 tunnel add tun3 mode ip6ip6 local 2001:db8:1::1 remote 2001:db8:1::2

ip link set dev tun3 up

ip address add 2001:db8:2:2::1/64 dev tun3


Just like IPIP6 these ones aren’t going to be widely used any soon.

# create an ipip6 tunnel

ip -6 tunnel add ${interface name} mode ipip6 local ${local endpoint address} remote ${remote endpoint address}

Examples: ip -6 tunnel add tun8 mode ipip6 local 2001:db8:1::1 remote 2001:db8:1::2

This type of tunnel will be widely used only when transit operators phase IPv4 out (i.e., not any soon).

# create an l2 gre tunnel device


Static GRE tunnels are traditionally used for encapsulating IPv4 or IPv6 packets,
but the RFC does not limit GRE payloads to L3 protocol packets.
It’s possible to encapsulate anything, including Ethernet frames.

However, in Linux, the gre encapsulation refers specifically to L3 devices,
while for an L2 device capable of transmitting Ethernet frames, you need to use the gretap encapsulation.

# L2 GRE over IPv4
ip link add ${interface name} type gretap local ${local endpoint address} remote ${remote endpoint address}

# L2 GRE over IPv6
ip link add ${interface name} type ip6gretap local ${local endpoint address} remote ${remote endpoint address}

These tunnels can be bridged with other physical and virtual interfaces.

Examples:

ip link add gretap0 type gretap local 192.0.2.1 remote 203.0.113.3

ip link add gretap1 type ip6gretap local 2001:db8:dead::1 remote 2001:db8:beef::2

# create an sit (6in4) tunnel

ip tunnel add ${interface name} mode sit local ${local endpoint address} remote ${remote endpoint address}


Examples:

ip tunnel add tun9 mode sit local 192.0.2.1 remote 198.51.100.3

ip link set dev tun9 up

ip address add 2001:db8:1::1/64 dev tun9

This type of tunnel is commonly used to provide an IPv4-connected network with IPv6 connectivity.
There are so-called “tunnel brokers” that provide it to everyone interested, e.g., Hurricane Electric’s tunnelbroker.net.

# default route

There is a shortcut for creating default routes.

ip route add default via ${address}/${mask}

ip route add default dev ${interface name}

These are equivalent to:

ip route add 0.0.0.0/0 via ${address}/${mask}

ip route add 0.0.0.0/0 dev ${interface name}


For IPv6 routes, default is equivalent to ::/0.

ip -6 route add default via 2001:db8::1

# delete all rules

ip rule flush

ip -6 rule flush

Notes: this operation is highly disruptive. Even if you have not configured any rules, some fundamental rules like from all lookup main rules are created for you by default.
On an unconfigured machine, you can see this:

$ ip rule show
0:	from all lookup local 
32766:	from all lookup main 
32767:	from all lookup default 

$ ip -6 rule show
0:	from all lookup local 
32766:	from all lookup main 

The from all lookup local rule is special and cannot be deleted. The from all lookup main is not, there may be valid reasons not to have it, e.g.,
if you want to route only traffic you created explicit rules for.
As a side effect, if you do ip rule flush, that rule will be deleted, which will make the system stop routing any traffic until you restore your rules.

# delete an address from an interface

ip address delete ${address}/${prefix} dev ${interface name}


Examples:

ip address delete 192.0.2.1/24 dev eth0

ip address delete 2001:db8::1/64 dev tun1

An interface name is required—the kernel will not try to automatically guess which interface you want to remove that address from.
Such a guess would not always be unambiguous: Linux does allow the same address to be configured on multiple interfaces, and it has valid use cases
(in the Cisco world, this is known as “unnumbered interfaces”).

# enable or disable arp on an interface

ip link set ${interface name} arp on

ip link set ${interface name} arp off

One may want to disable ARP to enforce a security policy and allow only specific MACs to communicate with the interface.
In this case, neighbor table entries for whitelisted MACs should be created manually,
or nothing will be able to communicate with that interface.

In most cases, it’s better to configure MAC policy on an access layer switch, though. Do not change this flag unless you are sure what you are going to do and why.

# general rule syntax

ip rule add ${options} <lookup ${table id or name}|blackhole|prohibit|unreachable>


Traffic that matches the ${options} (described below) will be routed according to the table with specified name/id instead of the “main”/254 table if the lookup action is used.

blackhole, prohibit, and unreachable actions work just like in the default table.

For IPv6 rules, use ip -6, the rest of the syntax is the same.

table ${table id or name} can be used as a shortcut for lookup ${table id or name}.

# link management

“Link” is another term for a network interface. Commands from the ip link family perform operations that are common for all interface types, like viewing link information or changing the MTU.

Historically, the ip link command could not create tunnels (IPIP, GRE etc.), VXLAN links, or L2TPv3 pseudowires.
Starting from at least iproute2 3.16, it could create anything except L2TPv3 interfaces, and this remains true as of iproute2 5.7.
A lot of time, old commands for specific interface types are still more convenient to use, though.

# modify a tunnel

ip tunnel change ${interface name} ${options}

Examples:

ip tunnel change tun0 remote 203.0.113.89

ip tunnel change tun10 key 23456

Note: Apparently, you can’t add a key to a previously unkeyed tunnel. Not sure if it’s a bug or a feature.
Also, you can’t change tunnel mode on the fly, for obvious reasons.

# monitor specific events

ip monitor ${event type}


Event type can be:

link
Link state: interfaces going up and down, virtual interfaces getting created or destroyed etc.
address
Link address changes.
route
Routing table changes.
mroute
Multicast routing changes.
neigh
Changes in neighbor (ARP and NDP) tables.

When there are distinct IPv4 and IPv6 subsystems, the usual -4 and -6 options allow you to display events only for the specified protocol.

ip -4 monitor route

ip -6 monitor neigh

ip -4 monitor address

# multipath routing

ip route add ${addresss}/${mask} nexthop via ${gateway 1} weight ${number} nexthop via ${gateway 2} weight ${number}

Multipath routes make the system balance packets across several links according to the weight (higher weight is preferred, so gateway/interface with weight 2 will get roughly two times more traffic
than another one with weight 1). You can have as many gateways as you want, and you can mix gateway and interface routes:

ip route add default nexthop via 192.168.1.1 weight 1 nexthop dev ppp0 weight 10

Warning: the downside of this type of load balancing is that packets are not guaranteed to be sent back through the same link they came in.
This is called “asymmetric routing”. For routers that simply forward packets and don’t do any local traffic processing, this is usually fine,
and in some cases even unavoidable.


If your system does some local processing (e.g. NAT), this may cause problems with incoming connections.
In that case, you should be using a stateful L4 load balancing setup instead.

# other special routes

There are a few other types of special purpose routes.

ip route add unreachable ${address}/${mask}

ip route add prohibit ${address}/${mask}

ip route add throw ${address}/${mask}

These routes make the system discard packets and reply with an ICMP error message to the sender.

Unlike blackhole routes, these can’t be recommended for stopping unwanted traffic (e.g., DDoS) because they generate a reply packet for every discarded packet and thus create an even greater traffic flow.
They can be good for implementing internal access policies, but a firewall is usually a better idea.

“Throw” routes may be used for implementing policy-based routing. In non-default, tables they stop the lookup process but don’t send ICMP error messages.

# overview of iproute2

iproute2 is the Linux networking toolkit that replaced net-tools (ifconfig, vconfig, route, arp etc.).
Most of the networking functionality is unified in the ip command. There’s also tc for managing traffic policies (QoS),
and ss (a netstat replacement), but this document is focused on the ip part.

iproute2 was originally written by Alex Kuznetsov and is now maintained by Stephen Hemminger.

# read a log file produced by rtmon

iproute2 includes a program called rtmon that serves essentially the same purpose but writes events to a binary log file instead of displaying them.
You can read those logs file with an ip monitor command.

ip monitor ${event type} file ${path to the log file}
rtmon [-family <inet|inet6>] [<route|link|address|all>] file ${log file path}

# routes with different metric

ip route add ${address}/${mask} via ${gateway} metric ${number}


Examples:

ip route add 192.168.2.0/24 via 10.0.1.1 metric 5

ip route add 192.168.2.0 dev ppp0 metric 10

If there are several routes to the same network with different metric value, the kernel prefers the one with the lowest metric.

:/>  Попытка использовать NanoCAD Plus 11 вместо AutoCad LT 2018

An important part of this concept is that when an interface goes down, routes that would be rendered useless by this event disappear from the routing table
(see the connected routes section), and the system will fall back to routes with higher metric values.

This feature is commonly used to implement backup connections to important destinations.

# run a process inside a namespace

ip netns exec ${namespace name} ${command}


Example: ip netns exec foo /bin/sh.

Note: assigning a process to a non-default namespace requires root privileges.

You can run any processes inside a namespace, in particular, you can run /sbin/ip itself. Commands like ip netns exec foo ip link list in this section are not special:
we are simply executing another copy of ip in a namespace. You can run an interactive shell inside a namespace as well.

# set human-readable link description

ip link set dev ${interface name} alias "${description}"

Examples: ip link set dev eth0 alias “LAN interface”.


Link aliases show up in the ip link show output, like this:

2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP mode DEFAULT qlen 1000
    link/ether 22:ce:e0:99:63:6f brd ff:ff:ff:ff:ff:ff
    alias LAN interface

# set rule priority

ip rule add ${options} ${action} priority ${value}

Examples:

ip rule add from 192.0.2.0/25 lookup 10 priority 10

ip rule add from 192.0.2.0/24 lookup 20 priority 20

Note: Rules are traversed from the lowest to the highest priority, and processing stops on the first match, so you need to put more specific rules before less specific ones.
The example above demonstrates rules for 192.0.2.0/24 and its subnet 192.0.2.0/25. If the priorities were reversed and the rule for /25 was placed after the rule for /24, it would never be reached.

# tunnel management


Tunnels are “network wormholes” that emulate a direct connection over a routed network by encapsulating entire packets into another protocol.

Linux currently supports IPIP (IPv4 in IPv4), SIT (IPv6 in IPv4), IP6IP6 (IPv6 in IPv6), IPIP6 (IPv4 in IPv6), GRE (virtually anything in anything), and VTI (IPv4 in IPsec).

Note that tunnels are created in the DOWN state; you need to bring them up.

In this section ${local endpoint address} and ${remote endpoint address} refer to addresses assigned to physical interfaces,
while ${address} refers to an address assigned to a tunnel interface.

# view only the route actually used by the kernel

ip route get ${address}/${mask}


Example: ip route get 192.168.0.0/24.

Note that in complex routing scenarios like multipath routing, the result may be “correct but not complete”, since it always shows only one route that will be used first.
In most situations, it’s not a problem, but never forget to look at the corresponding “show” command output too.

# view routes to a network and all its subnets

ip route show to root ${address}/${mask}

For example, if you use 192.168.0.0/24 subnet in your network and it’s broken into 192.168.0.0/25 and 192.168.0.128/25, you can see all those routes with
ip route show to root 192.168.0.0/24.


Note: the word “to” is optional in all “show” commands.

# view routes to a network and all supernets

ip route show to match ${address}/${mask}

If you want to view routes to 192.168.0.0/24 and all larger subnets, use ip route show to match 192.168.0.0/24.

Routers prefer more specific routes to less specific, so this is often useful for debugging in situations when traffic to a specific subnet is sent the wrong way because
a route to it is missing, but routes to larger subnets exist.

Ip-route(8) — iproute2 — debian testing — debian manpages

attach tunnel encapsulation attributes to this route.

ENCAPTYPE is a string specifying the supported
encapsulation type. Namely:

mpls – encapsulation type MPLS

ip – IP encapsulation (Geneve, GRE, VXLAN, …)

bpf – Execution of BPF program

seg6 – encapsulation type IPv6 Segment Routing

seg6local – local SRv6 segment processing

ioam6 – encapsulation type IPv6 IOAM

ENCAPHDR is a set of encapsulation attributes specific to the
ENCAPTYPE.

mpls
MPLSLABEL – mpls label stack with labels separated by /

ttlTTL – TTL to use for MPLS header or 0 to
inherit from IP header

ip
idTUNNEL_IDdstREMOTE_IP [ srcSRC ] [ tosTOS ] [ ttlTTL ] [
key ] [ csum ] [ seq ]

bpf
inPROG – BPF program to execute for incoming packets

outPROG – BPF program to execute for outgoing
packets

xmitPROG – BPF program to execute for
transmitted packets

headroomSIZE – Size of header BPF program will
attach (xmit)

seg6
mode inline – Directly insert Segment Routing Header after IPv6
header

mode encap – Encapsulate packet in an outer IPv6 header
with SRH

mode l2encap – Encapsulate ingress L2 frame within an
outer IPv6 header and SRH

SEGMENTS – List of comma-separated IPv6 addresses

KEYID – Numerical value in decimal representation. See
ip-sr(8).

seg6local
SEG6_ACTION [ SEG6_ACTION_PARAM ] [ count ] –
Operation to perform on matching packets. The optional count
attribute is used to collect statistics on the processing of actions.
Three counters are implemented: 1) packets correctly processed; 2) bytes
correctly processed; 3) packets that cause a processing error (i.e.,
missing SID List, wrong SID List, etc). To retrieve the counters related
to an action use the -s flag in the show command. The
following actions are currently supported (Linux 4.14 only).

End – Regular SRv6 processing as intermediate segment
endpoint. This action only accepts packets with a non-zero Segments Left
value. Other matching packets are dropped.

End.X nh6NEXTHOP – Regular SRv6 processing as
intermediate segment endpoint. Additionally, forward processed packets
to given next-hop. This action only accepts packets with a non-zero
Segments Left value. Other matching packets are dropped.

End.DX6 nh6NEXTHOP – Decapsulate inner IPv6
packet and forward it to the specified next-hop. If the argument is set
to ::, then the next-hop is selected according to the local selection
rules. This action only accepts packets with either a zero Segments Left
value or no SRH at all, and an inner IPv6 packet. Other matching packets
are dropped.

End.DT6 { table | vrftable }
TABLEID – Decapsulate the inner IPv6 packet and forward it
according to the specified lookup table. TABLEID is either a
number or a string from the file /etc/iproute2/rt_tables. If
vrftable is used, the argument must be a VRF device associated
with the table id. Moreover, the VRF table associated with the table id
must be configured with the VRF strict mode turned on
(net.vrf.strict_mode=1). This action only accepts packets with either a
zero Segments Left value or no SRH at all, and an inner IPv6 packet.
Other matching packets are dropped.

End.DT4 vrftableTABLEID – Decapsulate the inner
IPv4 packet and forward it according to the specified lookup table.
TABLEID is either a number or a string from the file
/etc/iproute2/rt_tables. The argument must be a VRF device
associated with the table id. Moreover, the VRF table associated with
the table id must be configured with the VRF strict mode turned on
(net.vrf.strict_mode=1). This action only accepts packets with either a
zero Segments Left value or no SRH at all, and an inner IPv4 packet.
Other matching packets are dropped.

End.DT46 vrftableTABLEID – Decapsulate the
inner IPv4 or IPv6 packet and forward it according to the specified
lookup table. TABLEID is either a number or a string from the
file /etc/iproute2/rt_tables. The argument must be a VRF device
associated with the table id. Moreover, the VRF table associated with
the table id must be configured with the VRF strict mode turned on
(net.vrf.strict_mode=1). This action only accepts packets with either a
zero Segments Left value or no SRH at all, and an inner IPv4 or IPv6
packet. Other matching packets are dropped.

End.B6 srh segsSEGMENTS [ hmacKEYID ] – Insert the specified SRH immediately after the IPv6
header, update the DA with the first segment of the newly inserted SRH,
then forward the resulting packet. The original SRH is not modified.
This action only accepts packets with a non-zero Segments Left value.
Other matching packets are dropped.

End.B6.Encaps srh segsSEGMENTS [ hmacKEYID ] – Regular SRv6 processing as intermediate segment
endpoint. Additionally, encapsulate the matching packet within an outer
IPv6 header followed by the specified SRH. The destination address of
the outer IPv6 header is set to the first segment of the new SRH. The
source address is set as described in ip-sr(8).

ioam6
mode inline – Directly insert IOAM after IPv6 header (default
mode).

mode encap – Encapsulate packet in an outer IPv6 header
with IOAM.

mode auto – Automatically use inline mode for local
packets and encap mode for in-transit packets.

tundstADDRESS – IPv6 address of the tunnel
destination (outer header), not used with inline mode.

typeIOAM6_TRACE_TYPE – List of IOAM data
required in the trace, represented by a bitfield (24 bits).

nsIOAM6_NAMESPACE – Numerical value to
represent an IOAM namespace. See ip-ioam(8).

sizeIOAM6_TRACE_SIZE – Size, in octets, of the
pre-allocated trace data block.

Routing types

This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.

More information about cookies

Synopsis         top

ip [ ip-OPTIONS ] route  { COMMAND | help }

       ip route { show | flush } SELECTORip route save SELECTORip route restoreip route get ROUTE_GET_FLAGS ADDRESS [ from ADDRESSiif STRING  ]
               [ oif STRING ] [ mark MARK ] [ tos TOS ] [ vrf NAME ] [
               ipproto PROTOCOL ] [ sport NUMBER ] [ dport NUMBER ]

       ip route { add | del | change | append | replace } ROUTESELECTOR := [ root PREFIX ] [ match PREFIX ] [ exact PREFIX ] [
               table TABLE_ID ] [ vrf NAME ] [ proto RTPROTO ] [ typeTYPE ] [ scope SCOPE ]

       ROUTE := NODE_SPEC [ INFO_SPEC ]

       NODE_SPEC := [ TYPE ] PREFIX [ tos TOS ] [ table TABLE_ID ] [
               proto RTPROTO ] [ scope SCOPE ] [ metric METRIC ] [ ttl-propagate { enabled | disabled } ]

       INFO_SPEC := { NH | nhid ID } OPTIONS FLAGS [ nexthop NH ] ...

       NH := [ encap ENCAP ] [ via [ FAMILY ] ADDRESS ] [ dev STRING ] [
               weight NUMBER ] NHFLAGSFAMILY := [ inet | inet6 | mpls | bridge | link ]

       OPTIONS := FLAGS [ mtu NUMBER ] [ advmss NUMBER ] [ as [ to ]
               ADDRESS ] rtt TIME ] [ rttvar TIME ] [ reordering NUMBER
               ] [ window NUMBER ] [ cwnd NUMBER ] [ ssthresh NUMBER ] [
               realms REALM ] [ rto_min TIME ] [ initcwnd NUMBER ] [
               initrwnd NUMBER ] [ features FEATURES ] [ quickack BOOL ]
               [ congctl NAME ] [ pref PREF ] [ expires TIME ] [
               fastopen_no_cookie BOOL ]

       TYPE := [ unicast | local | broadcast | multicast | throw |
               unreachable | prohibit | blackhole | nat ]

       TABLE_ID := [ local| main | default | all | NUMBER ]

       SCOPE := [ host | link | global | NUMBER ]

       NHFLAGS := [ onlink | pervasive ]

       RTPROTO := [ kernel | boot | static | NUMBER ]

       FEATURES := [ ecn | ]

       PREF := [ low | medium | high ]

       ENCAP := [ ENCAP_MPLS | ENCAP_IP | ENCAP_BPF | ENCAP_SEG6 |
               ENCAP_SEG6LOCAL ]

       ENCAP_MPLS := mpls [ LABEL ] [ ttl TTL ]

       ENCAP_IP := ip id TUNNEL_IDdst REMOTE_IP [ src SRC ] [ tos TOS ]
               [ ttl TTL ]

       ENCAP_BPF := bpf [ in PROG ] [ out PROG ] [ xmit PROG ] [
               headroom SIZE ]

       ENCAP_SEG6 := seg6 mode [ encap | inline | l2encap ] segsSEGMENTS [ hmac KEYID ]

       ENCAP_SEG6LOCAL := seg6local action SEG6_ACTION [
               SEG6_ACTION_PARAM ]

       ROUTE_GET_FLAGS :=  [ fibmatch  ]

Why learn “new” commands?

First, iproute2 is not new at all. It’s been a standard Linux tool since the early 2000’s
and has been included in every [GNU/]Linux distro by default for a long time.

:/>  Консоль, Терминал, Telnet и SSH - что это и зачем нужно?

A lot of networking features cannot be configured with the old tools and that list is only growing: VRF, network namespaces, policy-based routing, and so on.
The ip command provides access to all those features. It also offers a more uniform syntax: for example, ip link set dev eno1 nomaster
will work with bridge ports, link aggregation groups, and VRF; while the old approach would make you memorize the syntax of three different commands
for those tasks.

Добавление статических маршрутов

Добавлять статические маршруты нужно также в уже знакомом файле “/etc/netplan/02-network.yaml“:

$ sudo nano /etc/netplan/02-network.yaml
network:
  ethernets:
    ens18:
      dhcp4: no
      addresses: [ 172.28.90.75/20 ]
      routes:
       - to: default
         via: 172.28.80.10
       - to: 192.168.5.0/24
         via: 172.28.80.5
         on-link: true
      nameservers:
        addresses: [ 77.88.8.8, 77.88.8.1 ]
    ens19:
      dhcp4: no
      addresses: [ 192.168.0.10/24 ]
  version: 2

При добавлении маршрута нужно указать:

Применим настройки и проверим маршрут с помощью команды ip:

$ sudo netplan apply

$ ip route show
default via 172.28.80.10 dev ens18 proto static
172.28.80.0/20 dev ens18 proto kernel scope link src 172.28.90.75
192.168.0.0/24 dev ens19 proto kernel scope link src 192.168.0.10
192.168.5.0/24 via 172.28.80.5 dev ens18 proto static onlink

В примере выше – 192.168.5.0/24 via 172.28.80.5 dev ens18 proto static onlink – и есть наш дополнительный статический маршрут.

Команды таблицы маршрутизации

Я ничего не сказал про предпоследнюю строчку. А она самая интересная, ведь я ее добавил руками.
В чем ее смысл? Адреса диапазона 10.1-32.*.* я отправляю на шлюз 10.22.220.1. Пакеты на эти адреса не пойдут
в интернет, а останутся в локалке провайдера.

В случае Windows такой маршрут в таблицы маршрутизации был бы добавлен командой
route -p add 10.0.0.0 mask 255.224.0.0 10.22.220.1. -p означает, что маршрут постоянный,
он не должен удаляться после перезагрузки компьютера.

Статья и так уже получилась намного длинней обычных статей этого блога, так что я заканчиваю.
Пишите свои вопросы здесь, а если же вы хотите разобрать какие-то спицифические случаи настройки,
лучше обращайтесь на нашем форуме.

Настройка ip адреса

Вот настройка сетевых интерфейсов при помощи конфигурационных файлов в Ubuntu значительно отличается от Debian. Это потому-что в Ubuntu используется система для управления сетью – Netplan. И нужно будет изучить конфигурационные файлы и команды этой системы.

Конфигурационные файлы Netplan находятся в каталоге “/etc/netplan“, а конфигурационный файл созданный при установки системы – “/etc/netplan/00-installer-config.yaml“.

Посмотрим на этот конфиг с помощью утилиты cat:

$ cat /etc/netplan/00-installer-config.yaml
# This is the network config written by 'subiquity'
network:
  ethernets:
    ens18:
      dhcp4: true
    ens19:
      dhcp4: true
  version: 2

Такой формат конфигурационных файлов называется – YAML (произносится как “ямл”).

Разберём этот файл построчно:

Разбирать формат YAML не буду, просто покажу как назначить статичные ip адреса и отключить dhcp.

Число в имени файла – означает приоритет, и чем оно выше, тем выше приоритет у файла. Создадим новый конфиг, имя можно придумать любое, но чтобы этот файл стал главнее текущего, установим приоритет 02-:

$ sudo nano /etc/netplan/02-network.yaml
network:
  ethernets:
    ens18:
      dhcp4: no
      addresses: [ 172.28.90.75/20 ]
      routes:
       - to: default
         via: 172.28.80.10
      nameservers:
        addresses: [ 77.88.8.8, 77.88.8.1 ]
    ens19:
      dhcp4: no
      addresses: [ 192.168.0.10/24 ]
  version: 2

После создания конфигурационного файла проверим его на синтаксис:

$ sudo netplan generate

Если в выводе пусто, значит конфигурация верна.

Теперь можно применить настройки:

$ sudo netplan apply

После этого, вам придётся заново подключится к серверу по ssh, по другому ip адресу.

Итак, мы указали ip адреса для обоих интерфейсов, а также назначили на одном из низ шлюз по умолчанию (routes: – to default) и dns сервера (nameservers).

И запомните, на сервере Ubuntu 22.04, не нужно использовать утилиты ifdown и ifup. Здесь работает netplan, и применять настройки нужно с помощью этой утилиты, предварительно проверив конфигурацию.

Получение информации о сетевых интерфейсах

В прошлой статье мы разобрали настройку сети в системе Debian 11, а в этой разберём всё тоже самое но для Ubuntu 22.04.

Посмотреть на доступные сетевые интерфейсы мы точно также можем с помощью утилиты lshw. И на сервере Ubuntu эта утилита предустановлена.

$ sudo lshw -C network
  *-network:0
       description: Ethernet controller
       product: Virtio network device
       vendor: Red Hat, Inc.
       physical id: 12
       bus info: pci@0000:00:12.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: msix bus_master cap_list rom
       configuration: driver=virtio-pci latency=0
       resources: irq:11 ioport:e0e0(size=32) memory:fea93000-fea93fff memory:fe40c000-fe40ffff memory:fea00000-fea3ffff
     *-virtio3
          description: Ethernet interface
          physical id: 0
          bus info: virtio@3
          logical name: ens18
          serial: 02:6e:f0:fb:d4:71
          capabilities: ethernet physical
          configuration: autonegotiation=off broadcast=yes driver=virtio_net driverversion=1.0.0 ip=172.28.90.34 link=yes multicast=yes
  *-network:1
       description: Ethernet controller
       product: Virtio network device
       vendor: Red Hat, Inc.
       physical id: 13
       bus info: pci@0000:00:13.0
       version: 00
       width: 64 bits
       clock: 33MHz
       capabilities: msix bus_master cap_list rom
       configuration: driver=virtio-pci latency=0
       resources: irq:10 ioport:e100(size=32) memory:fea94000-fea94fff memory:fe410000-fe413fff memory:fea40000-fea7ffff
     *-virtio4
          description: Ethernet interface
          physical id: 0
          bus info: virtio@4
          logical name: ens19
          serial: 82:dd:88:27:00:a5
          capabilities: ethernet physical
          configuration: autonegotiation=off broadcast=yes driver=virtio_net driverversion=1.0.0 link=yes multicast=yes

В этом примере у меня два сетевых интерфейса: ens18 (02:6e:f0:fb:d4:71) и ens19 (82:dd:88:27:00:a5). При этом ip адрес назначен только на ens18 (172.28.90.34).

Мы уже знаем что утилита lshw в основном используется, чтобы узнать имя и возможности сетевой карты, то есть информацию о железе. А для получения настроек сетевых интерфейсов нужно использовать команду – ip. Работает эта команда точно также как в Debian, поэтому заострять на ней внимание не буду.

$ ip addr show ens18
2: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 02:6e:f0:fb:d4:71 brd ff:ff:ff:ff:ff:ff
    inet 172.28.90.34/20 brd 172.28.95.255 scope global dynamic ens18
       valid_lft 258376sec preferred_lft 258376sec
    inet6 fe80::6e:f0ff:fefb:d471/64 scope link
       valid_lft forever preferred_lft forever

$ ip addr show ens19
3: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 82:dd:88:27:00:a5 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::80dd:88ff:fe27:a5/64 scope link
       valid_lft forever preferred_lft forever

В примере выше видно, что ens18 имеет назначенный ip адрес, а ens19 нет. Но оба интерфейса активны (state UP).

Просмотр таблицы маршрутизации

Приведу вывод команды route print на моем стаионарном компьютере:

Сетевой адресМаска сетиАдрес шлюзаИнтерфейсМетрика
0.0.0.00.0.0.0192.168.1.1192.168.1.10020
127.0.0.0255.0.0.0On-link127.0.0.1306
127.0.0.1255.255.255.255On-link127.0.0.1306
127.255.255.255255.255.255.255On-link127.0.0.1306
192.168.1.0255.255.255.0On-link192.168.1.100276
192.168.1.100255.255.255.255On-link192.168.1.100276
192.168.1.255255.255.255.255On-link192.168.1.100276
244.0.0.0240.0.0.0On-link127.0.0.1306
244.0.0.0240.0.0.0On-link192.168.1.100276
255.255.255.255255.255.255.255On-link127.0.0.1306
255.255.255.255255.255.255.255On-link192.168.1.100276

Вот так мы можем просмотреть таблицы маршрутизации. Попробуем описать, что все это означает. Каждая строчка опреедляет, куда отправлять какие пакеты.
То есть для диапазона, задаваемого значениями в колонках “сетевой адрес” и “маска сети” создается сетевой маршрут.

Например, адрес 192.168.0.1 и маска 255.255.255.0 означают, что имеется в виду диапазон 192.168.0.*.
Маска всегда имеет вид, когда вначале стоят 255, в конце – нули, а последним ненулевым числом может быть степень двойки минус один.
Например, для маски 255.255.127.

Итак, если мы определились с диапазоном, мы должны понять, куда же компьютер будет направлять пакеты, если они предназначены
адресам из этого диапазона. Начнем с четвертой колонки. Она определяет тот адаптор, на который нужно отправлять пакеты.
Например, в данном случае, в ней встречаются 192.168.1.

100 – это адрес моей сетевой карты и 127.0.0.1 –
так называемая обратная петля. Пакеты “на этот адаптор” компьютер даже не будет пытаться отправлять куда-либо.
Если бы у меня была активна другая карта, например, WiFi, то в четвертой колонке встречался бы и е адрес.

Третья колонка определяет “шлюз” – тот маршрутизатор, которому нужно послать эти пакеты. В случае, когда там написано “On-link”,
имеется в виду, что никаких маршрутизаторов не нужно – адрес и так находится в прямой досягаемости. Последняя колонка – метрика.

Итак, давайте разберем описанные маршруты. На самом деле, самой важной является в данном случае первая строчка.
Она говорит, что для любого адреса (адрес 0.0.0.0 с маской 0.0.0.0 задает полный диапазон) есть маршрут
с использованием моей сетевой карты, и направить можно эти пакеты по адресу 192.168.1.1.

Поговорим про остальное. Три строчки про 127 – системные, связаны с тем, что эти адреса всегда должны возвращаться
на сам компьютер. Адреса диапазона 192.168.1.* являются локальной сетью, 192.168.1.100 – вообще наш адрес,
192.168.1.255 – специальный адрес для широковещательных пакетов в локальной сети.
Адреса 244.0.0.0 – тоже специальные зафиксированные адреса для широкого вещания, а две последние строчки
определяют сами адаптеры.

Но этот случай достаточно неинтересный. Посмотрим на таблица на моем роутере.
Внешний вид будет немного другой, поскольку на нем Линукс, и я вывожу соответствующие таблицы командой route -n.

Destination Gateway Genmask Flags MetricRef UseIface
10.0.20.43 0.0.0.0255.255.255.255UH000ppp0
192.168.1.00.0.0.0255.255.255.0U000br0
10.22.220.00.0.0.0255.255.255.0U000vlan1
10.0.0.010.22.220.1255.224.0.0UG000vlan1
127.0.0.00.0.0.0255.0.0.0U000lo
0.0.0.010.0.20.430.0.0.0UG000ppp0

Заметим сразу, что колонки немного изменились. На всех мы останавливаться не будем, существенной измененной колонкой является
последняя – вместо IP-адреса адаптора мы указываем его имя. Здесь lo – это “петля” (никуда не отправлять),
br0 – внутренняя сеть, ppp0 – внешняя, vlan0 – установленное vpn-содениение. Итак, разберем строчки.
Также в колонке с флагами буква G означает Gateway – шлюз, а H – Host, наш компьютер.

Последняя строчка – шлюз по умолчанию. Любой пакет мы может отправить на адрес 10.0.20.43.
Что интересно, это – наш собственный адрес, полученный при установке VPN – соединения!
Так всегда получается, когда установлено VPN-соединения, пакет, в первую очередь отправляем своему виртуальному интерфейсу,
где он инкапсулируется в другой пакет, который пойдет до реального шлюза. Естественно, в таблицах маршрутизации этого не видно.
Также к описанию этого соединения относится и первая строчка.

Настоящий шлюз мы видим в третей строчке – адресы диапазона 10.22.220.* отправляются на vlan1, шлюз,
предоставленный провайдером, коммуникатор, с которым мы соединены сетевым кабелем напрямую.
Вторая строчка говорит о том, что адреса диапазона 192.168.1.* – это локальная сеть, и пакеты
к ним нужно отправлять внутрь, а не вовне. Пятая – обычная информация про “локальные адреса”.

# create multiple gre tunnels to the same endpoint

ip tunnel add ${interface name} mode gre local ${local endpoint address} remote ${remote endpoint address} key ${key value}

Examples:

ip tunnel add tun4 mode gre local 192.0.2.1 remote 203.0.113.6 key 123

ip tunnel add tun5 mode gre local 192.0.2.1 remote 203.0.113.6 key 124

You can also specify keys in a dotted-decimal IPv4-like format.

Оставьте комментарий

Adblock
detector