Skip to content

Instantly share code, notes, and snippets.

@quark-zju
Created July 9, 2014 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quark-zju/aa0e91736d0ddd31c254 to your computer and use it in GitHub Desktop.
Save quark-zju/aa0e91736d0ddd31c254 to your computer and use it in GitHub Desktop.
Quick & naive upload traffic limit
#!/usr/bin/env ruby
# quick egress traffic limit for linux
# Usage: $0 dev kbps
MIN_RATE = 512
devs = []
rate = 0
dev_names = Dir['/sys/devices/**/net/*'].map{|x|File.basename(x)}
ARGV.each do |v|
if dev_names.include? v
devs.push v
else
rate = v.to_i
end
end
rate = MIN_RATE if rate < MIN_RATE && rate >= 0
if devs.empty?
puts "Usage: #$0 [dev1] [dev2] [kbps=#{MIN_RATE}]"
puts " #$0 eth0 # limit eth0 upload speed to #{MIN_RATE}kbps"
puts " #$0 eth0 eth1 256 # limit eth0 and eth1 upload speed to 256kbps"
puts " #$0 eth0 -1 # unlimit eth0 upload speed"
end
sudo_prefix = Process.uid == 0 ? '' : 'sudo '
devs.each do |dev|
system "#{sudo_prefix} tc qdisc del dev #{dev} root >/dev/null 2>/dev/null"
if rate < 0
puts "Unlimit #{dev}"
else
puts "Limit #{dev} to #{rate}kbps"
system "#{sudo_prefix} tc qdisc add dev #{dev} root tbf rate #{rate}kbit latency 500ms burst #{rate * 3 / 2}kbit"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment