Skip to content

Traffic Control (tc)

Linux Traffic Control (tc) is a kernel-level utility for managing network traffic, enabling precise shaping, prioritization, and monitoring of data flows. By leveraging queueing disciplines (qdiscs) and classes, administrators can enforce Quality of Service (QoS) policies, limit bandwidth, and ensure critical traffic receives priority. This guide demonstrates how to configure and manage traffic control rules on Linux systems.


Basic Setup and Concepts

Before shaping traffic, ensure tc is installed (typically pre-installed on Linux distributions). Verify the current configuration using:

tc qdisc show
tc class show

To create a root qdisc on a network interface (e.g., eth0), use:

sudo tc qdisc add dev eth0 root handle 1: htb

This creates a hierarchical token bucket (HTB) qdisc, which is ideal for bandwidth shaping. The handle 1: defines the root class, and subsequent classes are added under it.


Traffic Shaping with HTB

HTB allows you to define bandwidth limits for specific traffic flows. For example, to limit total bandwidth to 10 Mbps:

sudo tc class add dev eth0 parent 1: classid 1:10 htb rate 10mbit

This creates a class (1:10) under the root qdisc (1:) with a maximum rate of 10 Mbps. To further shape child traffic, add sub-classes:

sudo tc class add dev eth0 parent 1:10 classid 1:10 htb rate 5mbit
sudo tc class add dev eth0 parent 1:10 classid 1:20 htb rate 5mbit

These sub-classes (1:10 and 1:20) can be assigned to different traffic types (e.g., video streaming vs. file transfers).


Prioritization with PFIFO_FAST

For prioritizing critical traffic (e.g., VoIP), use the pfifo_fast qdisc, which supports three priority levels (0–2):

sudo tc qdisc add dev eth0 parent 1: handle 10: pfifo_fast priomap 1 1 2 2 2 2 0 0

This assigns higher priority to traffic with ToS (Type of Service) bits 1 and 2. To map specific traffic flows to priorities, use iptables or nftables to mark packets:

sudo iptables -t mangle -A PREROUTING -p udp --dport 5060 -j TOS --set-tos 0x10

This marks VoIP traffic (UDP port 5060) with a TOS value of 0x10, which pfifo_fast prioritizes.


Monitoring Traffic with tc

Use tc -s to inspect statistics for qdiscs and classes:

sudo tc -s qdisc show
sudo tc -s class show

This displays metrics like packets dropped, bytes transmitted, and average latency. For real-time monitoring, combine tc with tools like nstat or sar.


Key takeaways

  • HTB is essential for bandwidth shaping, enabling precise rate limits for different traffic classes.
  • PFIFO_FAST allows prioritization of critical traffic using ToS/DSCP markings.
  • tc -s provides granular insights into traffic statistics, aiding in QoS optimization.
  • Traffic control requires careful hierarchy management to avoid configuration conflicts.
  • Integrate tc with iptables or nftables for dynamic traffic classification and marking.