Android get public ip address programmatically

Android get public ip address programmatically

Hey, In this tutorial we are getting a mobile phone device IP address while the phone is connected to a mobile data connection or WiFi connection. This example demonstrates android get public ip address programmatically

Whenever you enable WiFi on your device and have an active connection to a WiFi network, your mobile data is temporarily disabled, Android Apps/Applications Mobile development this example demonstrates how do I get the IP address of an android device programmatically.

How to use TabLayout in ViewPager with RecyclerView

In this example, we will use Network Interface to get the IP address. So, before starting the code we need to know about NetworkInterface.

NetworkInterface

This class represents a Network Interface made up of a name, and a list of IP addresses assigned to this interface. It is used to identify the local interface on which a multicast group is joined. Interfaces are normally known by names such as "le0".

Loading...

Public methods

Resource : Network Interface

booleanequals(Object obj)Compares this object against the specified object.
static NetworkInterfacegetByIndex(int index)Get a network interface given its index.
static NetworkInterfacegetByInetAddress(InetAddress addr)Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to it.
static NetworkInterfacegetByName(String name)Searches for the network interface with the specified name.
StringgetDisplayName()Get the display name of this network interface.
byte[]getHardwareAddress()Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current privileges.
intgetIndex()Returns the index of this network interface.
Enumeration<InetAddress>getInetAddresses()Convenience method to return an Enumeration with all or a subset of the InetAddresses bound to this network interface.
List<InterfaceAddress>getInterfaceAddresses()Get a List of all or a subset of the InterfaceAddresses of this network interface.
intgetMTU()Returns the Maximum Transmission Unit (MTU) of this interface.
StringgetName()Get the name of this network interface.
static Enumeration<NetworkInterface>getNetworkInterfaces()Returns all the interfaces on this machine.
NetworkInterfacegetParent()Returns the parent NetworkInterface of this interface if this is a subinterface, or null if it is a physical (non-virtual) interface or has no parent.
Enumeration<NetworkInterface>getSubInterfaces()Get an Enumeration with all the subinterfaces (also known as virtual interfaces) attached to this network interface.
booleanisLoopback()Returns whether a network interface is a loopback interface.
booleanisPointToPoint()Returns whether a network interface is a point to point interface.
booleanisUp()Returns whether a network interface is up and running.
booleanisVirtual()Returns whether this interface is a virtual interface (also called subinterface).
booleansupportsMulticast()Returns whether a network interface supports multicasting or not.

How to get ip address of android device programmatically

There are few steps to get an IP address of device.

Step 1

Create a new project in Android Studio, go to File -> New Project and fill all required details to create a new project.

Step 2

Add the following code to res/layout/activity_main.xml.

Android Collapsing Toolbar With Image

Loading...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:layout_margin="20dp"
   android:orientation="vertical">

   <TextView
      android:id="@+id/getIPAddress"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="IP address of your Device"
      android:textStyle="bold"
      android:textSize="20sp" />

</RelativeLayout>

Step 3

Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">

      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Step 4

Add the following code to src/MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.widget.TextView;
import java.net.NetworkInterface;
import java.net.InetAddress;

public class MainActivity extends AppCompatActivity {
   TextView textView;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.getIPAddress);
      
      textView.setText("Your Device IP Address: " + getIPAddress(true));
   }
   
   public static String getIPAddress(boolean useIPv4) {
		try {
			List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
			for (NetworkInterface intf : interfaces) {
				List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
				for (InetAddress addr : addrs) {
					if (!addr.isLoopbackAddress()) {
						String sAddr = addr.getHostAddress().toUpperCase();
						boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
						if (useIPv4) {
							if (isIPv4)
								return sAddr;
						} else {
							if (!isIPv4) {
								int delim = sAddr.indexOf('%'); // drop ip6 port suffix
								return delim<0 ? sAddr : sAddr.substring(0, delim);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
}

Related posts

Write a comment