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" "$@"
fi

brctl addbr br0
brctl addif br0 eth0
ifconfig eth0 0.0.0.0 promisc up
ifconfig br0 172.27.0.2 netmask 255.255.255.0
route add default gw 172.27.0.1 br0

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

    ifconfig eth0 172.27.0.2 netmask 255.255.255.0
    route add default gw 172.27.0.1 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 172.27.0.2, replace that with your own IP address.
  2. My gateway has IP address 172.27.0.1, 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

Related