Secondary IP in its own netns namespace

Is there a way I can move a secondary IP into its own namespace while keeping the primary IP on the original device?

If I have 10.0.0.1 and 10.0.0.2 on device eth0, but I want 10.0.0.2 to be in its own netns test, the closest I've come to that involves adding a veth pair and a bridge, and moving the eth0 primary IP to the bridge:

  netns: test              netns: default
==============     ===============================
vethB:10.0.0.2 <-> vethA <-> br0:10.0.0.1 <-> eth0

Unfortunately moving the 10.0.0.1 IP off of eth0 will confuse a few opaque legacy applications on the box, so I'd prefer to keep that on eth0.


The Linux macvlan device is a workable solution here.

It instantiates a layer 2 subinterface which is a bona fide logical device, unlike the eth0:1 administrative fiction to manage secondary IPs, which I may then move into a network namespace and address. Example:

#  netns: test        netns: default
# ==============     ================
# test0:10.0.0.2 <->  eth0:10.0.0.1

# Create "test" network namespace
ip netns add test
ip netns exec test ip link set lo up

# Create subinterface and move to "test"
ip link add link eth0 name test0 type macvlan
ip link set test0 netns test

# Configure the subinterface
ip netns exec test ip addr add 10.0.0.2/24 brd + dev test0

This preserves the "primary" IP on eth0 and thus keeps the existing system more-or-less unaware of my hidden "secondary" IP.

Addendum for wifi interfaces

User pts points out that macvlan devices won't work if eth0 is a wifi interface. Instead, use interface type ipvlan mode 12.


A given device can only be in one namespace, see https://lwn.net/Articles/580893/ :

Aside from the loopback device, each network device (physical or virtual interfaces, bridges, etc.) can only be present in a single network namespace.

So your eth0 can only be in one. Your setup, with two virtual interfaces and a bridge is a solution to this problem. I do not understand what it changes for applications if the IP is tied to br0 instead of eth0, they should not see a difference. Otherwise you will need to provide more details. Did you really get problems, and if so, which ones, or do you just expect them?

If you can uses them, have a look at VLANs: you can put each of them (off the same physical interface) in different namespaces. This is detailed here: https://blog.scottlowe.org/2014/03/21/a-follow-up-on-linux-network-namespaces/

If you can not use a bridge or VLANs, you will need to setup some IP forwarding or NAT.