Accessing Local Name-Based Virtual Hosts From the Android Emulator
To test mobile versions of websites, it is useful to be able to connect to a web server on your local machine from a web browser on an Android emulator without having to expose the web server to the Internet. You can’t use the normal loop-back IP address of 127.0.0.1 because that refers to the emulated Android device itself. Instead you have to use 10.0.2.2 to connect to the host machine.
That’s fine if your local web server is serving a single site, but if you are using name-based virtual hosting to serve different sites depending on the host name of the request (with aliases for localhost defined in your machine’s hosts file), then you need to be making requests from the browser using the correct host name, not the IP address.
The Android emulator does not use the host machine’s hosts file for name resolution so attempting to access http://myvirtualhost in the emulator’s browser will not work. This is because the emulated Android device has it’s own hosts file, so you have to update this to map the virtual host names to the local machine.
The first step is to start the AVD with an increased partition size otherwise you may get an out of memory error when you try to save the modified hosts file:
emulator -avd MyAVD -partition-size 128
You then have to remount the system partition so that it is writeable:
Then copy the hosts file from the emulated device to the host machine:
adb pull /etc/hosts
Edit the hosts file so that it includes mappings for all relevant virtual host names:
127.0.0.1 localhost 10.0.2.2 myvirtualhost1 myvirtualhost2
Then copy the updated file back to the emulated device:
adb push hosts /etc/hosts
You should then be able to visit http://myvirtualhost1 in the emulator’s browser and see the correct site.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)