Skip to content

Instantly share code, notes, and snippets.

@frobware
Created February 21, 2016 22:31
Show Gist options
  • Save frobware/d97d2bae2030942f8819 to your computer and use it in GitHub Desktop.
Save frobware/d97d2bae2030942f8819 to your computer and use it in GitHub Desktop.
macvlan setup
#!/bin/bash -xeu
# let host and guests talk to each other over macvlan
# configures a macvlan interface on the hypervisor
# run this on the hypervisor (e.g. in /etc/rc.local)
# made for IPv4; need modification for IPv6
# meant for a simple network setup with only eth0,
# and a static (manual) ip config
# Evert Mouw, 2013
HWLINK=enp4s0
MACVLN=macvlan0
TESTHOST=www.google.com
# ------------
# wait for network availability
# ------------
while ! ping -q -c 1 $TESTHOST > /dev/null
do
echo "$0: Cannot ping $TESTHOST, waiting another 5 secs..."
sleep 5
done
# ------------
# get network config
# ------------
IP=$(ip address show dev $HWLINK | grep "inet " | awk '{print $2}')
NETWORK=$(ip -4 route list exact default | head -n1 | cut -d' ' -f3)
GATEWAY=$(ip -o route | grep default | awk '{print $3}')
# ------------
# setting up $MACVLN interface
# ------------
ip link add link $HWLINK $MACVLN type macvlan mode bridge
ip address add $IP dev $MACVLN
ip link set dev $MACVLN up
# ------------
# routing table
# ------------
# empty routes
ip route flush dev $HWLINK
ip route flush dev $MACVLN
# add routes
ip route add $NETWORK dev $MACVLN metric 0
# add the default gateway
ip route add default via $GATEWAY
@oreillymj
Copy link

GATEWAY=$(ip -o route | grep default | awk '{print $3}') won't work on systems with multiple adapters like this

ip -o route | grep default
default via 172.16.0.1 dev eth1
default via 192.168.2.1 dev eth0 proto dhcp src 192.168.2.105 metric 202

GATEWAY=$(ip -o route | grep default | grep $HWLINK | awk '{print $3}')

@frobware
Copy link
Author

frobware commented Nov 2, 2021

@oreillymj thanks.

I have literally no recollection for why I was doing this or why I made it a gist. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment