QEMU | Quick Networking for TCP/UDP

Networking with a guest in QEMU is often a headache, TUN/TAP, seriously? Too hectic, let’s stick to the basics, TCP/UDP based. Instead of setting up a really complex set of configuration files, wouldn’t it be easy to just emulate the network card, DHCP the guest, and let it work right out of the box?

Well certainly yes. QEMU can do all this very easily.

Cut the chase, hit the code:

#!/bin/sh
qemu="qemu-system-x86_64"
cpu_args="-cpu qemu64 -smp 2"
mem_args="-m 128M"
drive="-hda /media/fowlmanordisk1/devel/virtual/red.tvway"
net_args="-net user -net nic,model=rtl8139"
redirs="-redir tcp:8022::22"
${qemu} ${cpu_args} ${mem_args} ${drive} ${net_args} ${redirs} -nographic &

is one of my virtual servers’ running on Ubuntu server. Take a look at the network arguments:
-net user -net nic,model=rtl8139
Pretty simple? The QEMU emulator runs an inbuilt DHCP server, if the guest recognises the network card, and requests the configuration from the DHCP server, it acquires the required IP address, and viola! Instant access to the outside world. The file /etc/resolv.conf still needs to be configured to your preferable DNS servers. OpenDNS is usually a good solution.

Notice the -redir argument, it specifies that an issue to port 8022 on the outside be mapped to port 22 on the inside(guest). So basically you could ssh localhost -p 8022 and get access to your guest machine.

The -redir is as follows(from the QEMU manual pages):

-redir [tcp|udp]:[hostaddr]:hostport-[guestaddr]:guestport
         Redirect incoming TCP or UDP connections to the host port
         hostport to the guest IP address guestaddr on guest port
         guestport. If guestaddr is not specified, its value is x.x.x.15
         (default first address given by the built-in DHCP server). By
         specifying hostaddr, the rule can be bound to a specific host
         interface. If no connection type is set, TCP is used. This
         option can be given multiple times.

Enjoy virtual machines with QEMU.