I always forget how to connect to the internet in QEMU. Usually, I don’t perform any special configurations and simply use QEMU’s user mode networking. In this setup, I can’t ping 1.1.1.1, although I can ping google.com. When I was using NetBSD in QEMU, the internet was very slow, so I looked for a way to speed it up. The first method I considered was using a bridge, but bridging to a wireless Wi-Fi isn’t feasible. Eventually, I found that using NAT could be a solution1.
The operating system I am using is Alpine Linux. Before I can create the tap0 interface, I need to install iproute2:
doas apk add iproute2
After that, I created tap0.
doas ip tuntap add tap0 mode tap
doas ip addr add 192.168.100.1/24 dev tap0
Next, I enabled IP forwarding and set up the routing table:
doas sysctl net.ipv4.ip_forward=1
doas iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
i usualy create shell script for qemu
#!/bin/sh
set -xe
ISO="NetBSD-10.1-amd64.iso"
DISK="NetBSD.qcow2"
qemu-system-x86_64 \
-enable-kvm \
-cpu host \
-m 4G \
-smp 2 \
-hda $DISK \
-boot b \ # b: boot to hda, d: boot to cdroom
-cdrom $ISO \
-netdev tap,id=net0,ifname=tap0,script=no,downscript=no \
-device virtio-net-pci,netdev=net0 \
-object rng-random,filename=/dev/urandom,id=rng0 \
-device virtio-rng-pci,rng=rng0 \
-vga std -display sdl,gl=on
Don’t forget to create disk
qemu-img create -f qcow2 NetBSD.qcow2 20G
Set network like this in NetBSD
IP Address: 192.168.100.2
Netmask: 255.255.255.0
Gateway: 192.168.100.1
DNS: 1.1.1.1
To do this, you can run the following commands in NetBSD:
ifconfig vioif0 inet 192.168.1.100 netmask 255.255.255.0 up
route add default 192.168.1.1
echo "nameserver 1.1.1.1" > /etc/resolv.conf
Setting up QEMU with a NAT on Linux https://felipec.wordpress.com/2009/12/27/setting-up-qemu-with-a-nat/ ↩