For those of you who know, ping utility does not work on Android Emulator. This is because emulator has no ICMP support on QEMU with user mode networking. QEMU user networking mode details can be found here. The solution to get ping working on emulator is by adding another virtual network interface on the emulator.
We start with installing uml-utilities package on the host machine.
apt-get install uml-utilities
This would enable us to create a virtual interface on the underlying host. A virtual interface on the host can be created using following command
tunctl -u $(USER_NAME) -t tap0
Next, we start emulator by passing additional command line parameters to QEMU for creating new network interface on emulator
emulator -avd $(AVD_NAME) -qemu -net nic -net user -net nic -net tap,ifname=tap0,script=no,downscript=no
(The qemu parameters should be at the end. Note that -net nic -net user here indicates the default emulator interface eth0 and -net nic -net tap,ifname=tap0 stands for new interface eth1)
When the emulator boots, one can check if additional interface eth1 on the emulator was created by running.
adb shell netcfg
Now, we bring up the eth1 interface and assign IP to it .
adb shell ifconfig eth1 up 192.168.178.2 netmask 255.255.255.0
(Note: Don't bring down the default eth0 interface on the emulator as adb daemon and the adb server use this interface. adb shell would stop working.)
Similarly, we add a default gateway in the routing table of the emulator.
adb shell route add default gw 192.168.178.1 dev eth1
Further, on the host machine we execute the following command to bring up tap0 and assign ip address.
ifconfig tap0 up 192.168.178.1 netmask 255.255.255.0
We are almost done. You can now run ping inside the emulator.
ping -I eth1 192.168.178.2
Now, try some IP on the Internet say
ping -I eth1 www.google.com
This won't work yet. We need to forward all the traffic sent on tap0 host network interface to host interface dealing with Internet (either wlan0 or eth0). We add following rule to the IPTable on host for enabling this.
iptables -t nat -A POSTROUTING -o eth0 (or wlan0) -j SNAT --source-to $(YOUR_HOST_IP_ADDRESS)
Most importantly, don't forget to enable ip forwarding on the host
sysctl net.ipv4.ip_forward=1
We are done. Ping to external networks should work now.
Hey, I need to use it but when I try to start the emulator, I get this message:
qemu-system-x86_64: could not configure /dev/net/tun (tap0): Operation not permitted
I tried running as sudo, as in: sudo emulator -avd $(AVD_NAME) -qemu -net nic -net user -net nic -net tap,ifname=tap0,script=no,downscript=no
But when I do so the emulator can't be found. Do you know what can I do?