Wednesday, November 16, 2011

how to add multiple ip addresses to loopback and ping an AVD's host machine

From my Android Virtual Device I was trying to figure out how to connect to a service running on the same machine running the emulator.

For example, let's say I'm running Apache on my laptop, and also running the AVD on my laptop. In a browser on my laptop I can type "http://localhost/index.html" to test the index.html present in my Apache webroot.

But if I put "http://localhost/index.html" in the Android browser in the AVD, I don't get anything. That's because 'localhost' refers to the AVD itself, not the host outside the AVD.

This stackoverflow question saved the day: it turns out that from within the AVD you can ping the host machine at 10.0.2.2 - this is a kind of hard-coded virtual IP address in Android emulators for the host box.


Next, I wanted to make 10.0.2.2 go to localhost so that when I play a URL from the logs like http://10.0.2.2:8080/sms/srs?merch_txn_id=AK0AqgCkAMIAwwB5AOMAeA%3D%3D&i3p_db=ptsqa_fortumo3&i3p_host=10.0.2.2%3A5432&country=US
I don't want to have to replace 10.0.2.2 with localhost every time in every URL.

This part of the puzzle was solved by this very helpful link : I simply had to create a virtual IP address for the loopback device via:
ip -4 addr add 10.0.2.2/32 dev lo

After this we can see that 10.0.2.2 is an alias for the loopback interface, "lo":

[02:24:26] ~ $ ip addr
1: lo:  mtu 16436 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet 10.0.2.2/32 scope global lo
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever

No comments: