tc: Traffic Control for Network Emulation

tc (Traffic Control) is a powerful utility in Linux used to configure various aspects of the kernel’s packet scheduler. It allows you to manage Quality of Service (QoS), set bandwidth limits, and, crucially, emulate different network conditions such as latency, packet loss, and jitter. This network emulation functionality is provided by the netem (Network Emulator) queue discipline.

netem is an extremely useful tool for testing how applications behave under suboptimal network conditions without needing to physically manipulate the network infrastructure.

1. Adding Packet Loss

To introduce a specific percentage of packet loss on a network interface:

sudo tc qdisc add dev <interface_name> root netem loss 5%
# Example: Add 5% packet loss on eth0
sudo tc qdisc add dev eth0 root netem loss 5%

Command Breakdown:

  • sudo tc: Invokes the traffic control utility with superuser privileges.
  • qdisc: Specifies that we are managing a queuing discipline.
  • add: Adds a new queuing discipline.
  • dev <interface_name>: Specifies the network interface (e.g., eth0, ens33).
  • root: Applies the queuing discipline to the root of the interface’s outbound traffic.
  • netem: The network emulator queue discipline.
  • loss 5%: Configures netem to drop 5% of outgoing packets.

2. Resetting Traffic Control Rules

To remove all tc rules (including netem effects) from an interface, delete the root queue discipline.

sudo tc qdisc del dev <interface_name> root
# Example: Remove rules from eth0
sudo tc qdisc del dev eth0 root

3. Other netem Emulation Examples

Add Latency (Delay)

Introduce a fixed delay to outgoing packets.

sudo tc qdisc add dev <interface_name> root netem delay 100ms
# Add 100ms delay with 10ms jitter
sudo tc qdisc add dev <interface_name> root netem delay 100ms 10ms

Add Packet Corruption

Introduce a specified percentage of packet corruption.

sudo tc qdisc add dev <interface_name> root netem corrupt 1%

Duplicate Packets

Introduce a specified percentage of packet duplication.

sudo tc qdisc add dev <interface_name> root netem duplicate 1%

Combine Multiple Effects

You can combine effects by adding multiple parameters to a single netem rule.

sudo tc qdisc add dev <interface_name> root netem delay 100ms 10ms loss 1% corrupt 0.1%

4. Viewing Current tc Rules

To see the currently applied traffic control rules on an interface:

tc qdisc show dev <interface_name>

Warning: Using tc commands directly affects network traffic. Exercise extreme caution, especially in production environments, as misconfigurations can disrupt network connectivity. Always understand the impact of the commands before execution.