tc in Ubuntu

Introduction

Installation

apt install -y tc

Example

Let's ping the site topbicycle.ru

ping www.topbicycle.ru

PING www.topbicycle.ru (87.236.16.208) 56(84) bytes of data. 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=1 ttl=63 time=29.8 ms 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=2 ttl=63 time=35.3 ms 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=3 ttl=63 time=33.3 ms 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=4 ttl=63 time=41.0 ms

Ping comes back roughly every 30 ms

You need to find out which network interface is used to connect to the external internet.

You can do this with iftop or nethogs

In this example the interface we need is - enp0s3

tc -s qdisc ls dev enp0s3

qdisc pfifo_fast 0: root refcnt 2 bands 3 priomap 1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1 Sent 278060 bytes 3193 pkt (dropped 0, overlimits 0 requeues 0) backlog 0b 0p requeues 0

Set a delay of 100 ms

tc qdisc add dev enp0s3 root netem delay 100ms

Now, if we run ping, the requests will go 100 ms slower

ping www.topbicycle.ru

PING www.topbicycle.ru (87.236.16.208) 56(84) bytes of data. 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=1 ttl=63 time=130 ms 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=2 ttl=63 time=129 ms 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=3 ttl=63 time=127 ms 64 bytes from ssl.kirk.beget.com (87.236.16.208): icmp_seq=4 ttl=63 time=126 ms

Delete the rule

To remove the limit from the previous example, run

sudo tc qdisc del dev enp0s3 root

Inspect existing rules

Run

tc qdisc show

qdisc noqueue 0: dev lo root refcnt 2 qdisc cbq 1: dev enp0s3 root refcnt 2 rate 100Mbit (bounded,isolated) prio no-transmit qdisc pfifo_fast 0: dev enp0s8 root refcnt 2 bands 3 priomap 1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1 qdisc pfifo_fast 0: dev enp0s9 root refcnt 2 bands 3 priomap 1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1 qdisc pfifo_fast 0: dev enp0s10 root refcnt 2 bands 3 priomap 1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1 qdisc noqueue 0: dev virbr0 root refcnt 2 qdisc pfifo_fast 0: dev virbr0-nic root refcnt 2 bands 3 priomap 1 2 2 2 1 2 0 0 1 1 1 1 1 1 1 1

Limit the connection speed

Run

#!/bin/bash TC=/usr/sbin/tc DEV=enp0s8 LIMIT=3mbit DST_CIDR=192.168.56.109/24 U32="$TC filter add dev $DEV protocol ip parent 1:0 prio 1 u32" create () { echo "== SHAPING INIT ==" $TC qdisc add dev $DEV root handle 1:0 htb \ default 30 $TC class add dev $DEV parent 1:0 classid \ 1:1 htb rate $LIMIT $U32 match ip dst $DST_CIDR flowid 1:1 echo "== SHAPING CONFIG DONE ==" } clean () { echo "== CLEANUP INIT ==" $TC qdisc del dev $DEV root echo "== CLEANUP DONE ==" } clean create

Article author: Andrei Olegovich