Skip to content

Instantly share code, notes, and snippets.

@aojea
Last active May 1, 2024 20:29
Show Gist options
  • Save aojea/571c29f1b35e5c411f8297a47227d39d to your computer and use it in GitHub Desktop.
Save aojea/571c29f1b35e5c411f8297a47227d39d to your computer and use it in GitHub Desktop.
Poor man container/ network namespaces

Useful for troubleshooing network namespaces problems without having to create containers and the additional functionality

source netns.sh

netns_add ns1 192.168.0.2 192.168.0.1
netns_add ns2 192.168.0.3 192.168.0.1

ping -c 2 192.168.0.2
PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data.
64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=0.021 ms
^C
--- 192.168.0.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.021/0.021/0.021/0.000 ms

ping -c 2 192.168.0.3
PING 192.168.0.3 (192.168.0.3) 56(84) bytes of data.
64 bytes from 192.168.0.3: icmp_seq=1 ttl=64 time=0.021 ms
64 bytes from 192.168.0.3: icmp_seq=2 ttl=64 time=0.031 ms

--- 192.168.0.3 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 0.021/0.026/0.031/0.005 ms

#!/bin/bash
sysctl -w net.ipv4.ip_forward=1
netns_add () {
if [[ $# -ne 3 ]]; then
echo "Expected name ad IP address of the namespace" >&2
exit 2
fi
local name=$1
local ip=$2
local gw=$3
# Create network namespace
ip netns add ${name}
local truncated="$(echo $name | head -c 6)"
local ifname=veth"${truncated}"
ip netns exec ${name} ip link add name eth0 type veth peer name $ifname
ip netns exec ${name} ip link set netns 1 $ifname
ip netns exec ${name} ip addr add ${ip} dev eth0
ip netns exec ${name} ip link set up dev lo
ip netns exec ${name} ip link set up dev eth0
# Add ip route to the gateway
ip netns exec ${name} ip route add ${gw} dev eth0
# Add default route
ip netns exec ${name} ip route add default via ${gw} dev eth0
ip link set up dev ${ifname}
# routeback to the containerd
ip route add ${ip} dev ${ifname}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment