5 Minutes Guide To Linux Traffic Shaping
If you have your own home network with two or more computers, you definitely know all of the problems with concurrent access to internet channel. Most annoying problem is bandwidth sharing: when you are trying to use remote ssh connection to some server, and at the same time your wife/brother/friend decided to watch some new and very cool video clip at Google Video or YouTube, your connection will be stalled and you can forget about comfortable work. In this small article I will give you a simple solution for this problem and you will be able to do anything without worrying about traffic sharing problems!
First of all, you need to be connected to internet via Linux server. If your connection is some dumb hardware router, you can not use described advice.
If your server is Linux-driven, then use following instructions to make your life easier. My internet channel is connected to eth0 and LAN is on the eth1, and my channel is symmetrical 512Kbit/s cable connection, so all examples are based on this facts:
- Download htb.init script from sourceforge.
- Extract it, place htb.init file to /sbin/htb.init and change its permissions to make it executable:
# chmod +x /sbin/htb.init
- Create htb.init configuration and cache directories:
# mkdir -p /etc/sysconfig/htb # mkdir -p /var/cache/htb.init
- Go to htb.init configuration directory and create following configuration files for outgoing traffic:
- File ‘eth0′ with following content:
DEFAULT=30 R2Q=100
- File ‘eth0-2.root’ with following content:
# root class containing outgoing bandwidth RATE=512Kbit
- File ‘eth0-2:10.ssh’ with following content:
# class for outgoing ssh RATE=256Kbit CEIL=512Kbit LEAF=sfq RULE=*:22 PRIO=10
- File ‘eth0-2:30.default’ with following content:
# default class for outgoing traffic RATE=256Kbit CEIL=512Kbit LEAF=sfq PRIO=30
- File ‘eth0′ with following content:
- Next, create following configuration files for incoming traffic:
- File ‘eth1′ with following content:
DEFAULT=30 R2Q=100
- File ‘eth1-2.root’ with following content:
# root class containing incoming bandwidth RATE=512Kbit
- File ‘eth1-2:10.ssh’ with following content:
# class for incoming ssh RATE=256Kbit CEIL=512Kbit LEAF=sfq RULE=*:22, PRIO=10
- File ‘eth1-2:20.mytraf’ for your home computer IP with following content:
# class for my incoming traffic RATE=256Kbit CEIL=512Kbit LEAF=sfq RULE=192.168.0.2 # this is my ip PRIO=20
- File ‘eth1-2:30.default’ with following content:
# default class for outgoing traffic RATE=256Kbit CEIL=512Kbit LEAF=sfq PRIO=30
- File ‘eth1′ with following content:
- And last your step will be compile and run traffic control rules:
# /sbin/htb.init start #
If all described steps was successfully completed, you can use your connection to connect to any ssh host or to download files or to browse your favorite sites… Your connection will be divided between you and all other home network members. If you are alone in network now, you can use full bandwidth, if your neighbours will try to download something, bandwidth will be divided between you and them, but you connections will be as fast as when you were alone.
If you want to know more, you can use following resources:
- http://luxik.cdi.cz/~devik/qos/htb/manual/userg.htm
- http://www.docum.org/stef.coene/qos/faq/
- http://tldp.org/HOWTO/ADSL-Bandwidth-Management-HOWTO/index.html
Related posts:

11 Responses to this entry
[...] Интересная статья, поясняющая как можно настроить шейпер в линуксе с помощью htb.init. [...]
Огромное спасибо за столь познавательную статью. Но, к сожалению, для меня этот способ не применим – у меня один интерфейс и для локалки, и для выхода в интернет.
Как можно ограничить трафик для “локальщиков” (от меня забирают по ftp)?
Система Gentoo Linux.
Это можно сделать используя iproute2. Документ описывающий детали: Linux Advanced Routing & Traffic Control Howto. Доступен бесплатно
Видел и в е-донкей сети и в и-нете, только не помню где.
Здесь – http://lartc.org/
pdf ~700kB
Спасибо, почитаю…
Один знакомый нарисовал вот такую штуку…
мож кому поможет
#!/bin/sh
# \$speedrate=1+(92*SPEED_OUT)/100;
# Arg Name Example
# $1 $PPP_IFACE Interface name ppp0
# $2 $PPP_TTY The tty ttyS1
# $3 $PPP_SPEED The link speed 38400
# $4 $PPP_LOCAL Local IP number 12.34.56.78
# $5 $PPP_REMOTE Peer IP number 12.34.56.99
# $6 $PPP_IPPARAM Optional “ipparam” value foo
echo ‘ UP ‘ `date` Local $PPP_LOCAL, Remote $PPP_REMOTE, Iface $PPP_IFACE, IPParam $PPP_IPPARAM, Speed $PPP_SPEED>> /var/log/pptp.log
TCC=”/usr/bin/tcng”
shaper () {
INTERFACE=${1}
RATE_IN=${2}
RATE_OUT=${3}
# CEIL_OUT=${4}
IPADDR=${4}
echo ‘ ‘ `date` “!!! SHAPER !!! $INTERFACE-$IPADDR { $RATE_IN / $RATE_OUT }”>> /var/log/pptp.log
# echo ‘ ‘ `date` “!!! SHAPER !!! $INTERFACE-$IPADDR { $RATE_IN / $RATE_OUT-$CEIL_OUT }”>> /var/log/pptp.log
subscript () {
INTERFACE=${1}
RATE_IN=${2}
RATE_OUT=${3}
# CEIL_OUT=${4}
IPADDR=${4}
echo ”
#define IFACE $INTERFACE
#define IPADDR $IPADDR
#define SPEED1_IN $RATE_IN
#define SPEED1_OUT $RATE_OUT
#define R2Q 7
dev IFACE {
/* ЙУИПДСЭЙК ФТБЖЙЛ */
egress {
\$speedceil=SPEED1_OUT;
\$speedrate=\$speedrate=1+(92*SPEED1_OUT)/100;
class ( );
drop if 1 ;
htb ( r2q R2Q ) {
class ( rate \$speedrate kbps, ceil \$speedceil kbps ) {
\$police = class ( rate \$speedrate kbps, ceil \$speedceil kbps ) { sfq ( perturb 10s ); }
}
}
}
/* ЧИПДСЭЙК ФТБЖЙЛ */
\$p = bucket(rate SPEED_IN kbps,burst 10kB);
ingress {
class (1) if conform \$p && count \$p;
drop if 1;
}
}
” | $TCC | sed “s/drop\/\(drop\|pass\)/drop/”
}
SHAPER=$( subscript $INTERFACE $RATE_IN $RATE_OUT $IPADDR )
IFS_OLD=$IFS
IFS=$’\n’
for TC_CMD in $SHAPER; do
echo $TC_CMD >> /var/log/pptp.cmd.log
eval $TC_CMD
done
IFS=$IFS_OLD
}
echo “0″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/send_redirects
echo “0″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/accept_redirects
echo “1″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/secure_redirects
echo “0″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/accept_source_route
echo “0″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/bootp_relay
echo “0″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/proxy_arp
echo “0″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/log_martians
echo “1″ > /proc/sys/net/ipv4/conf/$PPP_IFACE/rp_filter
if [ "$PPP_IFACE" = "ppp99" ]; then
# обработка для внешнего канала
# shaper $PPP_IFACE 1024 128
else
# обработка для внутреннего канала
shaper $PPP_IFACE 64 256 $PPP_REMOTE
fi
Very useful guide. Thanks!
Regards,
Pablo from Argentina.
2_Andrey_
можно сделать средствами фтп сервера, например добавив в конфиг такую строку (proftpd)
TransferRate RETR,STOR,APPE 15 user !root
В данном случае мы ограничиваем закачку и скачивание всем пользователям на 15k кроме рута
подробнее http://andry.mine.nu/wordpress/?p=19
Thank you for a good traffic shapping guide, but I couldn’t understand what does eth1-2:10 mean? I mean that “10″. I’ve red about It. It’s about priority…But could someone explain It easily?
thanks
Please help – shaper for upload from IP
Плизз нужен шейпер чтоб можно было не только даунлоад резать но и аплоад…
Данное описание содержит ошибки:
Проблема 1:
При запуске
# /sbin/htb.init start
Получаем:
./htb.init: line 757: /var/cache/htb.init: Is a directory
**HTB: failed to compile HTB configuration!
Решение: Ошибка состоит в том, что мы создали папку /var/cache/htb.init а этого не следовало делать !!! Поскольку # /sbin/htb.init start пытается создать файл с таким же именем в данной папке и не может.
Проблема 2:
Все файлы которые мы создаем: eth0 и т.д. необходимо создавать не в папке /var/cache/htb.init а в папке # mkdir -p /etc/sysconfig/htb
Проблема 3:
может возникнуть предупреждение об ошибке типа:
find: warning: you have specified the -maxdepth option after a non-option argument (, but options are not positional (-maxdepth affects tests specified before it as well as those specified after it). Please specify options before other arguments.
В данном случае зайдите в файл htb.init и уберите знак # в строке HTB_BASIC=”yes”. В моей версии это была 412-я строка.