Dan is the founder of Rectangular Software, an independent UK software company that provides development services and builds its own mobile and web applications. Dan has over a decade of experience in the software industry, building a wide variety of systems including casino, poker and spread-betting platforms, mobile applications, e-commerce websites, and network security software. His other programming interests include artificial intelligence, particularly evolutionary computation, and functional programming in Haskell. He has authored, or contributed to, a number of open source Java projects. Dan has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

Accessing Local Name-Based Virtual Hosts From the Android Emulator

  • submit to reddit

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 because that refers to the emulated Android device itself.  Instead you have to use 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:

  adb remount

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:        localhost         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.


From http://blog.uncommons.org/2012/01/12/accessing-local-name-based-virtual-hosts-from-the-android-emulator/

Published at DZone with permission of its author, Dan Dyer.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)