Configuring Linux VLANs

Published

Setting up a VLAN for a network interface in Linux is a little bit convoluted. Let's write a Bash/ZSH function for simplifying the process.

$ vlan
Device not provided

    vlan $DEV $VLAN $SUBNET

    vlan eth0 42 10.31.155.1/27

This is a achieved by pasting the below function into your .bashrc / .zshrc and issuing a source .bashrc or source .zshrc correspondingly.

function vlan {
    DEV=$1
    VLAN=$2
    ADDR=$3

    HELP="

    vlan \$DEV \$VLAN \$SUBNET

    vlan eth0 42 10.31.155.1/27
"

    if [ -z "$DEV" ]; then
        echo "Device not provided"
        echo "$HELP"
        return 1
    fi

    ip link | grep "${DEV}: " >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "\"$DEV\" is not a valid device"
        echo "$HELP"
        return 1
    fi

    if [ -z "$VLAN" ]; then
        echo "VLAN not provided"
        echo "$HELP"
        exit 1
    fi
    REGEX='^[0-9]+$'
    if ! [[ $VLAN =~ $REGEX ]] ; then
        echo "\"$VLAN\" is not a number" >&2; exit 1
        echo "$HELP"
        return 1
    fi

    if [ -z "$ADDR" ]; then
        echo "IP address not provided"
        echo "$HELP"
        return 1
    fi
    ipcalc -cs $ADDR >/dev/null 2>&1
    if [ $? -ne 0 ]; then
        echo "\"$$ADDR\" is not a valid address"
        echo "$HELP"
        return 1
    fi

    VLAN_DEV=vlan_${VLAN}
    SUBNET="$(ipcalc $ADDR | grep Network: | cut -d' ' -f4)"

    sudo ip link add link $DEV name $VLAN_DEV type vlan id $VLAN
    sudo ip addr add $ADDR dev $VLAN_DEV metric 20
    sudo ip link set dev $VLAN_DEV up
}

If adding a full shell function is a bit too much for you, then the actual commands that need to be issued are the following.

sudo ip link add link wlp0s20f3 name vlan_42 type vlan id 42
sudo ip addr add 10.31.155.1/27 dev vlan_42 metric 20
sudo ip link set dev vlan_42 up

Tags: linux · network · vlan · interface · configure · nic