home | whoami

QEMU networking in 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

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 using IP from 192.168.100.0/24 network 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

It’s better to permanently save network configuration:

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

Notes

Masquerading should only be used for dynamically-assigned IP addresses.

If you have static IP then set it as a source IP implicitly for SNAT rule:

iptables -t nat -A POSTROUTING -o wlan0 -j SNAT --to 192.168.0.3
  1. QEMU/Networking
  2. NAT-HOWTO
  3. OpenBSD Network Configuration