0

I tried this code public class MainActivity extends Activity {

private static final String TAG = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView tv= (TextView) findViewById(R.id.textView2);
    String a=getLocalIpAddress();
      tv.setText(a);

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
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 a= inetAddress.getHostAddress();

                     return a;
                    }
                }
            }
        } catch (SocketException ex) {
           // Log.e(tag, ex.toString());
        }
        return "";
    }
}

this gives me ip address like 00ff:22ff:.... but I want it like 192.168.3.3... format ip address is depreciated is there any other method so that I could get formatted address

Alex Bravo
  • 1,601
  • 2
  • 24
  • 40

1 Answers1

-1

The address you're getting is the IPv6 one. What you're trying to get is the IPv4, so try using:

if ((!inetAddress.isLoopbackAddress()) && (InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress()))) { ... }

Instead of:

if (!inetAddress.isLoopbackAddress()) { ... }
nKn
  • 13,691
  • 9
  • 45
  • 62
  • Then please accept the question, both for reputation but overall in order to let other users with the same question know that this solution worked for you. – nKn Feb 14 '14 at 17:59
  • Please don't answer questions which have already been answered -- especially more than once. Further, your answer is only partial, and the new process will only find the *first* ip4 address which isn't a loopback. On devices with multiple interfaces (i.e. wifi and 4G) this may not return the active connection. – 323go Feb 14 '14 at 23:36