Bridged networking in KVM

One of the advantages of VMWare is that it has easy to set up bridged networking. However, I love Open Source so I started to experiment with KVM, the Kernel-based Virtual Machine.

Setting up bridging is a bit daunting, but not that complex once you’ve gotten the hang of it. I placed everything in a script for easy invocation. One of the features I wanted was that ending the script should tear down the bridged network, even when pressing Ctrl+C. This is my script:

#!/bin/bash -x

if [ "$USER" != 'root' ]; then
    echo "Restarting as root"
    exec sudo "$0" "$@"

brctl addbr br0
brctl addif br0 eth0
ifconfig eth0 promisc up
ifconfig br0 netmask
route add default gw br0

function restoreNet {
    ifconfig br0 down
    brctl delif br0 eth0
    brctl delbr br0

    ifconfig eth0 netmask
    route add default gw eth0

trap restoreNet EXIT

kvm \
    -localtime \
    -hda kvm-xp.qcow \
    -m 512 \
    -usb -usbdevice tablet \
    -net nic \
    -net tap \

Some of the features are:

  1. It starts bridging eth0 and the virtual machine’s network. This means that the VM can do a DHCP query and get an address from my DHCP server, for instance.
  2. The bridge is always removed when the script ends.
  3. The mouse simulates a tablet. This allows for absolute positioning, which you’ll notice allows your mouse to transparently move between your host system and the VM.
  4. Any commandline arguments you give to the script are passed to KVM.
  5. To create and remove the bridge, the script needs to run as root. If you didn’t run it as root, it automatically uses sudo.

Things you’ll probably want to edit:

  1. My desktop uses a fixed IP address, replace that with your own IP address.
  2. My gateway has IP address, replace that with your gateway/router address.
  3. My desktop uses eth0 to connect to the network. If you use another device, replace it.
  4. I use this setup to run Windows XP in KVM. The Windows installation is stored in kvm-xp.qcow, replace that with the harddisk image you want to use.

Enjoy! If you have any questions or remarks, post a comment below.

dr. Sybren A. Stüvel
dr. Sybren A. Stüvel
Open Source software developer, photographer, drummer, and electronics tinkerer