QEMU networking in NAT mode on Linux host

tags: qemu, linux, openbsd, netbsd

NAT mode

To configure networking on QEMU in NAT mode, bring up the tap interface tap0 and assign IP address to it:

ip tuntap add tap0 mode tap
ip addr add 192.168.100.1/24 dev tap0
ip link set tap0 up

Enable kernel IP forwarding and masquerading on internet connected interface:

echo 1 > /proc/sys/net/ipv4/ip_forward

iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE

In my case, it’s wlan0 wireless interface.

If you have static IP addresses, then you can set it as a source IP implicitly for SNAT rule(instead of masquerading):

iptables -t nat -A POSTROUTING -o wlan0 -j SNAT --to 192.168.0.3

Run your VM as following:

qemu-system-x86_64 -m 512 \
    -enable-kvm \
    -net nic,model=virtio,macaddr=00:00:00:00:00:01 \
    -net tap,ifname=tap0,script=no,downscript=no \
    openbsd66.img

Bridge mode

Create bringe

brctl addbr br0
ip link set dev br0 up
ip addr add 192.168.100.1/24 dev br0

Prepare the network 2 – the tun/tap for the virtual machine

ip tuntap add tap0 mode tap
brctl addif br0 tap0

Inside your VM, configure network interface and use 192.168.100.1 as a default route.

OpenBSD guest

ifconfig em0 192.168.100.2/24 up
route add default 192.168.100.1

To permanently save network configuration run:

echo "inet 192.168.100.2 255.255.255.0" > /etc/hostname.em0
echo "192.168.100.1" > /etc/mygate
sh /etc/netstart

NetBSD guest

ifconfig wm0 192.168.100.3/24 up
route add default 192.168.100.1

Save network configuration:

cat > /etc/ifconfig.wm0 << EOF
up
192.168.100.3 netmask 255.255.255.0
EOF

echo 'defaultroute="192.168.100.1"' >> /etc/rc.conf
sh /etc/rc.d/network restart
  1. QEMU/Networking
  2. NAT-HOWTO
  3. OpenBSD Network Configuration
  4. QEMU Documentation/Networking/NAT