Step-by-step instructions to configure network in QEMU with advantages:

  • virtual machine is visible as any other host on the network
  • good networking performances

Warning

Without further improvements, this method only works if your computer has a wired conexion



Bridge setup

This is meant to be run once (until the computer restarts or the unset network script is called.

It automatically gets (override if needed):

NIC:network interface name
MY_IP:your IP address on the $NIC network
GATEWAY:the default gateway

Then the script creates a bridge device and adds your network to the bridge.

#!/bin/sh
NIC=$(ip route show | sed -n '/^default/ {s/.*dev //; s/ .*//; p}')
MY_IP=$(ip addr show dev $NIC | sed -n '/inet /s/^ *inet \+\([0-9.]\+\).*/\1/p')
GATEWAY=$(ip route show | sed -n '/^default/s/.*via \(.*\)dev.*/\1/p')

sudo sysctl net.ipv4.ip_forward=1
sudo sysctl net.bridge.bridge-nf-call-ip6tables=0
sudo sysctl net.bridge.bridge-nf-call-iptables=0
sudo sysctl net.bridge.bridge-nf-call-arptables=0
echo 1 | sudo dd of=/proc/sys/net/ipv4/ip_forward

# make bridge
sudo ip link add br0 type bridge

# add me to brige
sudo ip addr flush dev $NIC
sudo ip link set $NIC master br0

# -- old tap setup --

# Configure host network (using bridge)
#sudo dhclient br0

sudo ip addr add $MY_IP/24 dev br0
sudo ip route add default via $GATEWAY
sudo ip link set dev br0 up

setup specific tap0 device (guest network interface)

This script just creates a new TAP device for the guest VM

It also adds this TAP device to the bridge

#!/bin/sh
NIC=$1
if [ -z "$NIC" ]; then
    echo "Missing tap device name to create !! (ex: tap0)"
    exit 1
fi
# Create TAP iface & connect it to bridge too
sudo ip tuntap add name $NIC mode tap
sudo ip link set $NIC master br0 up
sudo tunctl -u $USER -t $NIC

Run QEMU

With $image as VM image, $TAP as tap device name and $macaddr as mac address:

qemu \
    -vga virtio -display gtk,gl=off \
    -enable-kvm \
    -m 1024 \
    -device virtio-net-pci,netdev=net0,mac=$macaddr \
    -netdev tap,id=net0,ifname=$TAP,script=no,downscript=no \
    -serial stdio \
    -boot order=c  \
    -drive if=virtio,file=$image

If you run a single VM you can omit the ,mac=$macaddr part

unset network (after simulation)

If you want to revert the effect of the previous scripts, run that kind of command:

#!/bin/sh
NIC=enp0s25

sudo ip link set dev br0 down
sudo ip link set dev tap0 down
# detach bridge & delete it

sudo ip link set dev $NIC nomaster
sudo ip link set dev tap0 nomaster

sudo ip link del br0
sudo ip link del tap0

sudo systemctl restart network

Note

This script only removes the first TAP device !