Linux simulates network packet loss and latency

  • 2021-01-22 08:23:28
  • OfStack

netem and tc:

netem is a network emulation module available in kernel versions 2.6 and above. This function module can be used to simulate complex Internet transmission performance in a good LAN, such as low bandwidth, transmission delay, packet loss and so on. Many distributions of Linux that use the Linux 2.6 kernel (or above) have this kernel feature turned on, such as Fedora, Ubuntu, Redhat, OpenSuse, CentOS, Debian, and so on.

tc is a tool in the Linux system. Its full name is traffic control (flow control). tc can be used to control how netem works. In other words, if you want to use netem, at least two conditions are required. One is that netem functionality is included in the kernel, and the other is that tc is present.

It is important to note that the flow control introduced in this article can only control the outgoing action, not the receiving action. At the same time, it directly affects the physical interface. If you control the physical eth0, then the logical network card (for example, eth0:1) will also be affected. (Note: Multiple network cards in a virtual machine can be treated as multiple physical network cards in the virtual machine.)

Linux has an tc tool, traffic control, which can be used to simulate network packet loss and latency. When developing the backend server, if we want to know whether the server will perform well in a specific network loss situation, we can use tc to simulate the loss rate.

Simulation of packet loss

The following command can simulate packet loss: 10% of packets leaving the eth0 port will be lost at random:

sudo tc qdisc add dev eth0 root netem loss 10%

Simulation of delay

Packs leaving the eth0 port will be delayed by 40ms:

sudo tc qdisc add dev eth0 root netem delay 40ms

Packet loss and latency in specific scenarios

Note that the command described above works for the entire eth0 port, that is, any packet going out of eth0 will cause random packet loss or delay. But sometimes we just want packet loss and latency to apply to a destination address, so how do we do that?

sudo tc qdisc add dev eth0 root handle 1: prio
sudo tc qdisc add dev eth0 parent 1:3 handle 30: netem loss 13% delay 40ms
sudo tc filter add dev eth0 protocol ip parent 1:0 u32 match ip dst match ip dport 36000 0xffff flowid 1:3

The above command, we tell tc, results in a 13% loss and a 40ms delay for packets sent to, while packets sent to other destination addresses will not be affected.

Delete rules

Okay, after simulating packet loss and latency, remember to remove the rule:

sudo tc qdisc del dev eth0 root


Related articles: