cantona_7
cantona_7

Reputation: 1177

How to feed the IP of the device automatically in android

At the moment, I am giving the emulator IP address manually. After doing some research,I found out that If my device is connected to Wifi, I can use the following method.

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

But in my case it is not connected to wifi(Connected to LAN),How can I do it in this scenario ?

This what I have at the moment. I would like to have my app choose its IP ADDRESS automatically.

String url = "0.0.0.0"; // emulator ip MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setDataSource(url);

Upvotes: 0

Views: 393

Answers (2)

Vijaya Varma Lanke
Vijaya Varma Lanke

Reputation: 611

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()) {
                String ip = inetAddress.getHostAddress();
                Log.i(TAG, "***** IP="+ ip);
                return ip;
            }
        }
    }
} catch (SocketException ex) {
    Log.e(TAG, ex.toString());
}
return null;
}

using getHostAddress : IP=fe70::75ca:a16d:ea5a:.......

using hashCode and Formatter you will get the actual IP.

Upvotes: 1

cantona_7
cantona_7

Reputation: 1177

The answer from Varma Lanke works fine. But it returns the IP in reverse order. In order to solve that

Instead of this line

String ip = Formatter.formatIpAddress(inetAddress.hashCode());

Use this

String ip = inetAddress.getHostAddress();

For more details. Have a look here getting device Ip

Upvotes: 0

Related Questions