Skip to content

Instantly share code, notes, and snippets.

@Martyrshot
Last active December 9, 2022 15:35
Show Gist options
  • Save Martyrshot/30b370e2d11123e9500707e35e9d0205 to your computer and use it in GitHub Desktop.
Save Martyrshot/30b370e2d11123e9500707e35e9d0205 to your computer and use it in GitHub Desktop.
Using tc to add network latency, jitter, and network reliability
#! /bin/bash
# Depends on iproute2 package
INTERFACE="eth0" # This is the network interface being used to send and receive traffic
# (if multiple interfaces are being used, must run tc on each)
LATENCY="100ms" # The latency to be artificially added to the connection
# (only affects outbound packets)
LATENCY_JITTER="10ms" # How jitter is set. A random value between +/- $LATENCY_JITTER
# Will be added to $LATENCY. In this case let $JITTER = random(-10ms, 10ms)
# The artificial latency will be $LATENCY + $JITTER
DROP_PERCENTAGE="1%" # This indicates the percentage of packets which will be artificially dropped
BANDWIDTH="50mbps" # This sets the maximum bandwidth of an interface, in this case 50 Megabytes per second
# See the RATES section in tc's man page for the various units supported
if [[ $1 == "RESET" ]]
then
# Deleting the rule we have previously set reverts the interface back to default
tc qdisc del dev $INTERFACE root
else
tc qdisc add dev $INTERFACE root netem delay $LATENCY $LATENCY_JITTER rate $BANDWIDTH loss $DROP_PERCENTAGE
if [[ $? != 0 ]]
then
# if the above command fails, then there must be a rule already set. So replace it instead.
echo "Replacing pre-existing rule"
tc qdisc repalce dev $INTERFACE root netem delay $LATENCY $LATENCY_JITTER rate $BANDWIDTH loss $DROP_PERCENTAGE
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment