Pages

Subscribe:

Sunday, February 27, 2011

Getting the IP address of Android Emulator in code.




Following code snippet explains the way to get the IP address of the Android Emulator.

public String getLocalIpAddress() {
    try {
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface intf = en.nextElement();
            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                InetAddress inetAddress = enumIpAddr.nextElement();
                if (!inetAddress.isLoopbackAddress()) {
                    return inetAddress.getHostAddress().toString();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}
Remark
From within your app, you can simply refer to the emulator as 'localhost' or 127.0.0.1. Web traffic is routed through your development machine, so the emulator's external IP is whatever IP has been assigned to that machine by your provider. The development machine can always be reached from your device at 10.0.2.2.

3 comments:

Hemant Mahajan said...

I am not much comfortable with android development, but i know java very well. Can you please specify the packages which i have to import? I think util and IO package could work but i am not much confident whether it would work in android or not.

Raja Sekhar said...

http://learnandroiddevelopment.blogspot.com/2012/01/java-api-and-libraries-supported-in.html

Appzuniverse said...

Good article, its easy to understand about ip address of android emulator..
Android app development company, Mobile App Development Company

Post a Comment