Skip to content

Instantly share code, notes, and snippets.

@isofew
Created October 7, 2020 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isofew/a8db3f06ce9b449fd2ab29677919efc4 to your computer and use it in GitHub Desktop.
Save isofew/a8db3f06ce9b449fd2ab29677919efc4 to your computer and use it in GitHub Desktop.
create a net namespace and set up relevant addresses and routes
#! /bin/bash
if [ $# -ne 3 ]
then
echo Usage: $0 NS HOST_IP GUEST_IP
exit 1
fi
NS=$1
HOST_IP=$2
GUEST_IP=$3
HOST_IF=veth-$HOST_IP
GUEST_IF=veth-$GUEST_IP
# create net namespace
ip netns add $NS
# set up local loopback
ip netns exec $NS ip link set dev lo up
# create a pair of veth to link host and guest
ip link add $HOST_IF type veth peer name $GUEST_IF
ip link set $GUEST_IF netns $NS
# set up host interface
ip link set dev $HOST_IF up
ip addr add $HOST_IP/24 dev $HOST_IF
ip route add $GUEST_IP dev $HOST_IF
# set up guest interface
ip netns exec $NS ip link set dev $GUEST_IF up
ip netns exec $NS ip addr add $GUEST_IP/24 dev $GUEST_IF
ip netns exec $NS ip route add $HOST_IP dev $GUEST_IF
# set guest's default route via host
ip netns exec $NS ip route add default via $HOST_IP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment