How to forward a port from guest to host in qemu (kvm)
Minimal working setup
I can access both the host and external network with this QEMU command:
qemu-system-x86_64 \
-append 'root=/dev/vda console=ttyS0' \
-device rtl8139,netdev=net0 \
-drive file=./out/buildroot/build/default/x86_64/images/rootfs.ext2.qcow2,format=qcow2,if=virtio,snapshot \
-enable-kvm \
-kernel ./out/linux/default/x86_64/arch/x86/boot/bzImage \
-machine pc \
-netdev user,id=net0 \
-nographic \
-serial mon:stdio \
;
Then in the host, setup a file server on port 8000:
python -m SimpleHTTPServer 8000
nc -kl 0.0.0.0 8000
also works, but on one of my host systems it only worked with 0.0.0.0
but not localhost
.
Now in the guest:
# Done by init in most non-minimal systems.
ifup -a
ip route
This gives:
default via 10.0.2.2 dev eth0
10.0.2.0/24 dev eth0 scope link src 10.0.2.15
which tells us that the port we need is 10.0.2.2
:
cd /tmp
wget 10.0.2.2:8000
cat index.html
Tested with the following images:
- minimal QEMU + Buildroot setup
- Ubuntu amd64 cloud image: https://askubuntu.com/questions/281763/is-there-any-prebuilt-qemu-ubuntu-image32bit-online/1081171#1081171
Tested on an Ubuntu 18.10 host, QEMU 2.12.