How to set a two-way networking with qemu/kvm

Here is an example for debian and kvm.

On a host machine:

sudo kvm -net tap,script=/etc/kvm/kvm-ifup -net nic -m 256 -hda debian-lenny.img -curses
ifconfig tap0 192.168.5.1

In a virtual machine:

echo 'iface eth0 inet static
        address 192.168.5.2
        netmask 255.255.255.0
        gateway 192.168.5.1' >> /etc/network/interfaces

Can I haz internets on my guest now?

On a host system:

echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

In a guest system:

echo 'nameserver 8.8.8.8' > /etc/resolv.conf