Android Get IP Address

In this post, you can learn android source code to fetch the internet network IP address of the android device. Create a new android project and then in the main activity update the below code units.

ActivityMain.java

package com.udhaya.ip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  try {
   for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
              NetworkInterface intf = en.nextElement();
              for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                  InetAddress inetAddress = enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                  TextView ipView= (TextView) findViewById(R.string.ip);
                  ipView.setText(inetAddress.getHostAddress());
                  }
              }
          }
  } catch (Exception e) {
   Log.e("------------", e.toString());
  }
   }
}

Also, in the android manifest file, update the Uses Permission as mentioned below.
       
 <uses-permission android:name="android.permission.INTERNET" />

No comments:

Post a Comment

My Profile