Pejman Moghadam / Scripts

Bandwidth share using tc

Public domain


#!/usr/bin/bash
# Userside interface = $INTIF = receive of user = $DOWNLINK control
# Internet interface = $EXTIF = send of user = $UPLINK control
# Users = 172.16.20.10 172.16.20.254 

INTIF="eth0"
EXTIF="eth1"

DOWNLINK="128"
UPLINK="64"

MINDOWN="28"
MINUP="10"

LAN="172.16.20.10 172.16.20.254" 

iptables -t mangle -F
tc qdisc del dev ${INTIF} root > /dev/null 2>&1
tc qdisc del dev ${EXTIF} root > /dev/null 2>&1

tc qdisc add dev ${INTIF} root handle 1: htb 
tc qdisc add dev ${EXTIF} root handle 1: htb


tc class add dev ${INTIF} parent 1: classid 1:1 htb rate ${DOWNLINK}kbit ceil ${DOWNLINK}kbit
tc class add dev ${EXTIF} parent 1: classid 1:1 htb rate ${UPLINK}kbit ceil ${UPLINK}kbit


COUNT=1
HANDLE=1
for IP in $LAN; do

  tc class add dev ${INTIF} parent 1:1 classid 1:1${COUNT} htb rate ${MINDOWN}kbit ceil ${DOWNLINK}kbit
  tc filter add dev ${INTIF} parent 1: protocol ip prio 1 handle ${HANDLE} fw classid 1:1${COUNT}
  iptables -t mangle -A FORWARD -o ${INTIF} -d ${IP} -j MARK --set-mark ${HANDLE}

  HANDLE=$( expr ${HANDLE} + 1 )

  tc class add dev ${EXTIF} parent 1:1 classid 1:1${COUNT} htb rate ${MINUP}kbit ceil ${UPLINK}kbit
  tc filter add dev ${EXTIF} parent 1: protocol ip prio 1 handle ${HANDLE} fw classid 1:1${COUNT}
  iptables -t mangle -A FORWARD -o ${EXTIF} -s ${IP} -j MARK --set-mark ${HANDLE}

  COUNT=$( expr ${COUNT} + 1 )
  HANDLE=$( expr ${HANDLE} + 1 )

done

BY: Pejman Moghadam
TAG: tc, iptables, bash-script, bash, traffic-control
DATE: 2007-11-27 00:18:06


Pejman Moghadam / Scripts [ TXT ]