Qemu + Network Bridging on FreeBSD 7.0

From FBSD_tips

Jump to: navigation, search

[edit] Goals

after having read the qemu page on teh freebsd wiki I was not satisfied with my network setup. I had the following in mind:

  • automatic dynamic set up of tap interfaces when I start a virtual machine
  • the setup needs to work with qemu-launcher

so I wrote a script to do just that. It is a first Version that probably still needs some edits but it works for me. Before using it, read the comments on top of the script.


#!/bin/bash

# This script sets up bridged networking with qemu on FreeBSD
#
# 
#caveats:
# * the script assumes that the tap interfaces are created in sequential order
#   (eg tap12 is not created before tap5)
# * if there is one network bridge found, the script will use that one bridge
#   to attach the tap interfaces to no matter what you had in mind when
#   creating that bridge. If there is more than one, the script will create its
#   own and bridge $nic and the tap devices created by qemu together
#
# Those are not a technical limit, it is possible to script that, I just did
# not do it (yet).
#
#usage:
# in qemu-launcher set nic setting to "create tap device"
# * put in this script in the field "TUN/TAP configuration script:" in
#   quemu-launcher. when not using qemu launcher, use this script as
#   configuration script on command line.
# * put this script with command line option -e surrounded with $( ) into the field
#   "Name of the Network Interface:" in qemu-launcher. just
#   like $(name_of_this_script -e)
# * adjust settings in this script (nic, IFCONFIG and $SUDO - leave SUDO empty
#   if you do not want to use sudo)
# * set up sudo to let your user execute ifconfig without entering a password
#

# standard nic
nic=fxp0

# ifconfig command
IFCONFIG=/sbin/ifconfig
SUDO=sudo

#needs to be empty at first
bridge=

#echo "tap interface: $@"
[[ $@ == "-e" ]] && {
# echo the next tap device to be created - stupid qemu-launcher....
  tap=$($SUDO $IFCONFIG |grep tap|cut -d: -f1|tail -n1)
  tnum=$(echo $tap|tr -d a-z)
  [[ -n $tnum ]] && ((tnum+=1))
  num=${tnum:-0}
  echo tap${tnum}
  exit
}


# check if there is already a bridge:
# if there is more than one bridge, this script creates its own and bridges
# that with $nic
[[ $($SUDO $IFCONFIG |grep -c bridge) -eq 1 ]] && bridge=$($SUDO $IFCONFIG |grep bridge|cut -d: -f1)

[[ -z $bridge ]] && {
  bridge=$($SUDO $IFCONFIG bridge create)
  $SUDO $IFCONFIG $nic 0.0.0.0
  $SUDO $IFCONFIG $bridge addm $nic
  $SUDO /sbin/dhclient $bridge
}

# check which tap device was created by qemu
tap=$($SUDO $IFCONFIG | grep tap|cut -d: -f1|tail -n 1)

echo created tap device: $tap  
$SUDO $IFCONFIG $bridge addm $tap
$SUDO $IFCONFIG $bridge up 

$SUDO $IFCONFIG $tap 0.0.0.0

true

Place this script in ~/bin, make it executable and follow the instructions on the setup in the header to set things up.

Personal tools