Skip to content

Instantly share code, notes, and snippets.

@adam-hanna
Last active July 20, 2024 12:47
Show Gist options
  • Save adam-hanna/326111dbe059af5a3c813083fe51d1ca to your computer and use it in GitHub Desktop.
Save adam-hanna/326111dbe059af5a3c813083fe51d1ca to your computer and use it in GitHub Desktop.
Create and connect macvlan network namespaces

This tutorial was written using Red Hat Fedora 30 but may be similar on other distros.

Discover

You should have an eth0, but if you $ ifconcig -a and don't see it, you should do $ nmcli device status to determine which device is connected to your wifi/ethernet.

Create macvlans and network spaces

$ sudo ip link add macvlan1 link eth0 type macvlan mode bridge
$ sudo ip link add macvlan2 link eth0 type macvlan mode bridge
$ sudo ip netns add net1
$ sudo ip netns add net2
$ sudo ip link set macvlan1 netns net1 # attach net1 to macvlan1
$ sudo ip link set macvlan2 netns net2 # attach net2 to macvlan2

Start and connect to services

Much of this was taken from this excellent blog post.

# start a server listening on port 5000
$ sudo ip netns exec net1 /bin/bash -c 'while (sleep 1); do echo "hello from net1"; done | nc -lk 5000'

# in another window, confirm our server is up
$ sudo ip netns exec net1 lsof -i
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
nc      9794 root    3u  IPv6 269762      0t0  TCP *:commplex-main (LISTEN)
nc      9794 root    4u  IPv4 269763      0t0  TCP *:commplex-main (LISTEN)

# however, we can't connect just yet
$ sudo ip netns exec net1 nc -v localhost 5000

# That’s because the loopback network device, the one named lo, is DOWN
$ sudo ip netns exec net1 ip link list
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
19: macvlan1@if4: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether ce:e9:d1:6e:e1:31 brd ff:ff:ff:ff:ff:ff link-netnsid 0
    
# let's bring it up
$ sudo ip netns exec net1 ip link set lo up
$ sudo ip netns exec net1 ip link list     
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
19: macvlan1@if4: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/ether ce:e9:d1:6e:e1:31 brd ff:ff:ff:ff:ff:ff link-netnsid 0

# Now, from inside the net1 namespace, we can connect to the server
$ sudo ip netns exec net1 nc localhost 5000
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1
hello from net1

Cleaning up

$ sudo ip -all netns delete 
# or
$ sudo ip netns | xargs -I {} sudo ip netns delete {} 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment