Skip to content

Instantly share code, notes, and snippets.

@x-yuri
Last active May 7, 2025 14:52
Show Gist options
  • Save x-yuri/c55dffbe2cb8d21019a515f2372ba972 to your computer and use it in GitHub Desktop.
Save x-yuri/c55dffbe2cb8d21019a515f2372ba972 to your computer and use it in GitHub Desktop.
netns + veth

netns + veth

a.sh:

ip netns add myns
ip link add vethhost type veth peer name vethguest
ip addr add 10.255.255.2/24 dev vethhost
ip link set vethhost up
ip link set vethguest netns myns
ip netns exec myns ip addr add 10.255.255.3/24 dev vethguest
ip netns exec myns ip link set vethguest up

ip a | grep -E 'state \w+' --color=always | tail -1
ip netns exec myns ip a | grep -v lo: | grep -E 'state \w+' --color

socat TCP4-LISTEN:8080,bind=10.255.255.2,fork SYSTEM:'echo -e \"HTTP/1.1 200 OK\r\n\r\ntest\"' &
ip netns exec myns curl 10.255.255.2:8080
kill $!

ip netns exec myns ip route add default via 10.255.255.2
ip netns exec myns ping -c 1 8.8.8.8
ip netns exec myns curl google.com

ip link del vethhost
ip netns del myns

If docker is installed:

$ iptables -I DOCKER-USER -i vethhost -o wlo1 -j ACCEPT
$ iptables -I DOCKER-USER -i wlo1 -o vethhost -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
$ iptables -t nat -A POSTROUTING -s 10.255.255.0/24 ! -o vethhost -j MASQUERADE

b.sh:

ip netns add myns
ip link add vethhost type veth peer name vethguest
ip link set vethhost up
ip link set vethguest netns myns
ip netns exec myns ip addr add 10.255.255.2/24 dev vethguest
ip netns exec myns ip link set vethguest up
ip link add mybridge type bridge
ip addr add 10.255.255.1/24 dev mybridge
ip link set mybridge up
ip link set vethhost master mybridge

ip a | grep -E 'state \w+' --color=always | tail -2
ip netns exec myns ip a | grep -v lo: | grep -E 'state \w+' --color

socat TCP4-LISTEN:8080,bind=10.255.255.1,fork SYSTEM:'echo -e \"HTTP/1.1 200 OK\r\n\r\ntest\"' &
ip netns exec myns curl 10.255.255.1:8080
kill $!

ip netns exec myns ip route add default via 10.255.255.1
ip netns exec myns ping -c 1 google.com
ip netns exec myns curl google.com

ip link del mybridge
ip link del vethhost
ip netns del myns

If docker is installed:

$ iptables -I DOCKER-USER -i mybridge -o wlo1 -j ACCEPT
$ iptables -I DOCKER-USER -i wlo1 -o mybridge -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
$ iptables -t nat -A POSTROUTING -s 10.255.255.0/24 ! -o mybridge -j MASQUERADE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment