2012-10-23 22 views
4

我是linux新手,我的目標是使用tc命令(或其他命令)爲「eth0」或「lo」創建一個簡單的流量控制像ifconfig或iptables,但我不認爲我需要它們)。如何使用「tc」命令對特定端口進行簡單流量控制

我的內核是2.6.18-238.el5 GNU/Linux,我用的是redhat。

我的腳本是:

tc qdisc del dev $DEV root 
tc qdisc add dev $DEV root handle 1: htb default 10 
tc class add dev $DEV parent 1: classid 1:10 htb rate $DNLD 
tc filter add dev $DEV parent 1: protocol ip u32 match ip dport $input_port 0xffff flowid 1:10 

而$ DNLD是帶寬限制,$ DEV是爲eth0或Lo和$ input_port是我想要限制端口。

我已經閱讀了很多互聯網上的網頁,並且明白這是應該如何寫的,但是這條線不限制特定的端口,而是所有的端口。

我也嘗試使用「運動」,但它也不起作用。 所以我不明白是什麼問題。

另一個奇怪的事情是,限制帶寬似乎是工作,和復位線似乎是藏漢工作,(這是第一行: TC隊列規定德爾開發$ DEV根)

但儘管如此,輸出線後,我寫它是: 「RTNETLINK答案:沒有這樣的文件或目錄」 ,我不知道爲什麼,如果它造成任何損害。

如果您需要任何其他信息,請讓我知道。 如果有人能幫助我,我會很高興。 提前致謝。

回答

1

我不知道這是不是你正在尋找的東西,但是這是一個你可以編輯和運行的腳本。我用它來扼殺我的連接並測試網絡應用程序。

#!/bin/bash 
# 
# tc uses the following units when passed as a parameter. 
# kbps: Kilobytes per second 
# mbps: Megabytes per second 
# kbit: Kilobits per second 
# mbit: Megabits per second 
# bps: Bytes per second 
#  Amounts of data can be specified in: 
#  kb or k: Kilobytes 
#  mb or m: Megabytes 
#  mbit: Megabits 
#  kbit: Kilobits 
# To get the byte figure from bits, divide the number by 8 bit 
# 

# 
# Name of the traffic control command. 
TC=/sbin/tc 

# The network interface we're planning on limiting bandwidth. 
IF=`ip addr | grep 2: | cut -d' ' -f2 | cut -d: -f1` 

# Latency 
LAT_1=200ms   # Base latency 
LAT_2=50ms   # Plus or minus 
LAT_3=25%   # Based on previous packet % 
# Dropping packets 
DROP_1=5%   # Base probability 
DROP_2=25%   # Based on previous packet % 
# Bandwidth 
#DNLD=33kbps   # DOWNLOAD Limit 
#UPLD=33kbps   # UPLOAD Limit 
DNLD=1Mbps   # DOWNLOAD Limit 
UPLD=1Mbps   # UPLOAD Limit 

# IP address of the machine we are controlling 
IP=`ip addr | grep "inet " | tail -1 | cut -d' ' -f6 | cut -d/ -f1` 

# Filter options for limiting the intended interface. 
U32="$TC filter add dev $IF protocol ip parent 1:0 prio 1 u32" 

# We'll use Hierarchical Token Bucket (HTB) to shape bandwidth. 
# For detailed configuration options, please consult Linux man 
# page. 

#$TC qdisc add dev $IF root handle 2: netem delay $LAT_1 $LAT_2 $LAT_3  loss $DROP_1 $DROP_2 
$TC qdisc add dev $IF root handle 2: netem delay $LAT_1 $LAT_2 $LAT_3 loss $DROP_1 $DROP_2 
$TC qdisc add dev $IF parent 2: handle 1: htb default 30 
$TC class add dev $IF parent 1: classid 1:1 htb rate $DNLD 
$TC class add dev $IF parent 1: classid 1:2 htb rate $UPLD 
$U32 match ip dst $IP/32 flowid 1:1 
$U32 match ip src $IP/32 flowid 1:2 

# The first line creates the root qdisc, and the next three lines 
# create three child qdisc that are to be used to shape download 
# and upload bandwidth. 
# 
# The 5th and 6th line creates the filter to match the interface. 
# The 'dst' IP address is used to limit download speed, and the 
# 'src' IP address is used to limit upload speed. 

echo Limit to $DNLD on $IF for $IP 
相關問題