QEMU networking in NAT mode on Linux host

tags: qemu, linux, openbsd, netbsd

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 \
    -net tap,ifname=tap0,script=no,downscript=no \
    openbsd66.img

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