Jiechao Wang
Jiechao Wang

Reputation: 932

Get local IP address of the PC in Android

I am running some Android code in an Android emulator on a PC. I want to get the local IP address of the PC in my Android code, not sure whether this is possible...

I've checked the following post how to get ip address of pc in android emulator through code But looks like it can only give me the public IP address of the PC.

Thanks.

Upvotes: 3

Views: 4112

Answers (2)

davidcesarino
davidcesarino

Reputation: 16209

You can check my own answer here in order to verify the routes to various devices accessible to your Android emulator instance:

Host machine can be reached using IP address 10.0.2.2 from the emulator.

These are the IP addresses as reached from the emulator:

  • 10.0.2.1, Router/gateway address.
  • 10.0.2.2, Special alias to your host loopback interface (i.e., 127.0.0.1 on your development machine)
  • 10.0.2.3, First DNS server
  • 10.0.2.4 / 10.0.2.5 / 10.0.2.6, Optional second, third and fourth DNS server (if any)
  • 10.0.2.15, The emulated device's own network/ethernet interface
  • 127.0.0.1, The emulated device's own loopback interface

The full list with instructions can be found in the Android documentation at "Emulator Networking".

Upvotes: 2

Corey Scott
Corey Scott

Reputation: 2440

Generally an android device or emulator should be thought of as a separate computer from your development computer.

That said if you want the connect to the local computer from the android emulator/device then here are 2 options for you.

  1. Use a internal DNS that points a name to your local pc, you could even use this override the "live" url if that is what you want.

  2. Use BuildConfig.DEBUG flag or similar mechanics to switch between live and debug URLs/resources

e.g. To switch between a live URL when I export and debug when testing i use:

public final class MyAppConstants
{
    // url base for all requests to my API
    public static final String BASE_URL;

    // auto-switch between live and debug urls based on usage
    static 
    {
        if (BuildConfig.DEBUG)
        {
            URL_BASE = "http://debug.server.com/";
        }
        else
        {
            URL_BASE = "http://live.server.com/";
        }
    }
}

Upvotes: 0

Related Questions