Last active
February 15, 2020 20:39
-
-
Save ovidiu-ionescu/5f359e2063ddc8325239306014566a15 to your computer and use it in GitHub Desktop.
Creates a network namespace and a network connection between that and the current namespace. Can run multiple servers on the same port and all interfaces
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
if (( $EUID != 0 )); then | |
echo "Please run this as sudo $0" >&2 | |
exit 1 | |
fi | |
function create_space { | |
NS=$1 | |
ETH=$2 | |
IP_LOCAL=$3 | |
IP_REMOTE=$4 | |
BRIDGE=$5 | |
DEFAULT_GATEWAY=$6 | |
# Create a new network namespace | |
ip netns add $NS | |
# Bring loopback interface up in the namespace | |
ip netns exec $NS ip link set dev lo up | |
# Create a veth interface with two ends | |
ip link add ${ETH}host type veth peer name ${ETH}remote | |
# move one end into the other namespace | |
ip link set ${ETH}remote netns $NS | |
# Assign an ip address and bring the interface up in the namespace | |
ip netns exec $NS ip addr add ${IP_REMOTE}/24 dev ${ETH}remote | |
ip netns exec $NS ip link set ${ETH}remote up | |
ip netns exec $NS ip route add default via $DEFAULT_GATEWAY | |
# Assign an ip address and bring the interface up in the current namespace | |
ip addr add ${IP_LOCAL}/24 dev ${ETH}host | |
ip link set ${ETH}host up | |
# connect it to the bridge | |
ip link set ${ETH}host master $BRIDGE | |
} | |
ip link add br0 type bridge | |
ip addr add 192.168.0.1/24 dev br0 | |
ip link set br0 up | |
create_space netns1 veth1_ 192.168.0.2 192.168.0.3 br0 192.168.0.1 | |
create_space netns2 veth2_ 192.168.0.4 192.168.0.5 br0 192.168.0.1 | |
# sudo ip link delete br0 | |
# sudo ip netns list | awk '{print $1}' | sudo xargs ip netns delete | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment