It’s fairly easy to access your localhost from an Android emulator. The Android documentation explains that 10.0.2.2 is a special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine).
However, if you want to access a domain name (instead of an IP address) it becomes a little trickier. I wanted to use a domain name to validate the behaviour of my Android code when accessing a HTTPS website.
Let’s say you want that
your-test-ssl-domain.com resolves in 10.0.2.2. There are two options:
/etc/hostson the Android emulator (note: the emulator doesn’t read/use your localhost /etc/hosts)
- Setup your localhost DNS to answer 10.0.2.2 when he is asked to resolve
There are several blog posts which explains how to modify /etc/hosts on the Android emulator. I went for the second option.
At startup, the emulator reads the list of DNS servers that your system is currently using. Since Ubuntu 12.04, Network-Manager uses Dnsmasq to speed up DNS queries. By default, Dnsmasq doesn’t use
/etc/hosts, but it is possible to force it like this:
echo '10.0.2.2 your-test-ssl-domain.com' >> /etc/hosts
echo 'addn-hosts=/etc/hosts' > /etc/NetworkManager/dnsmasq.d/etc-hosts
service network-manager restart
Restart your emulator. Android will resolve
your-test-ssl-domain.com in 10.0.2.2.