• April 24, 2024

Android Studio Ip Address

How to get IP address of the device from code? - Stack Overflow

How to get IP address of the device from code? – Stack Overflow

Is it possible to get the IP address of the device using some code?
asked May 19 ’11 at 20:29
6
This is my helper util to read IP and MAC addresses. Implementation is pure-java, but I have a comment block in getMACAddress() which could read the value from the special Linux(Android) file. I’ve run this code only on few devices and Emulator but let me know here if you find weird results.
// permissions


// test functions
tMACAddress(“wlan0”);
tMACAddress(“eth0”);
tIPAddress(true); // IPv4
tIPAddress(false); // IPv6
import *;
//import;
public class Utils {
/**
* Convert byte array to hex string
* @param bytes toConvert
* @return hexValue
*/
public static String bytesToHex(byte[] bytes) {
StringBuilder sbuf = new StringBuilder();
for(int idx=0; idx <; idx++) { int intVal = bytes[idx] & 0xff; if (intVal < 0x10) ("0"); (HexString(intVal). toUpperCase());} return String();} * Get utf8 byte array. * @param str which to be converted * @return array of NULL if error was found public static byte[] getUTF8Bytes(String str) { try { return tBytes("UTF-8");} catch (Exception ex) { return null;}} * Load UTF8withBOM or any ansi text file. * @param filename which to be converted to string * @return String value of File * @throws if error occurs public static String loadFileAsString(String filename) throws { final int BUFLEN=1024; BufferedInputStream is = new BufferedInputStream(new FileInputStream(filename), BUFLEN); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFLEN); byte[] bytes = new byte[BUFLEN]; boolean isUTF8=false; int read, count=0; while(((bytes))! = -1) { if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF) { isUTF8=true; (bytes, 3, read-3); // drop UTF8 bom marker} else { (bytes, 0, read);} count+=read;} return isUTF8? new String(ByteArray(), "UTF-8"): new String(ByteArray());} finally { try{ ();} catch(Exception ignored){}}} * Returns MAC address of the given interface name. * @param interfaceName eth0, wlan0 or NULL=use first interface * @return mac address or empty string public static String getMACAddress(String interfaceName) { List interfaces = (tNetworkInterfaces());
for (NetworkInterface intf: interfaces) {
if (interfaceName! = null) {
if (! tName(). equalsIgnoreCase(interfaceName)) continue;}
byte[] mac = tHardwareAddress();
if (mac==null) return “”;
StringBuilder buf = new StringBuilder();
for (byte aMac: mac) ((“%02X:”, aMac));
if (()>0) leteCharAt(()-1);
return String();}} catch (Exception ignored) {} // for now eat exceptions
return “”;
/*try {
// this is so Linux hack
return loadFileAsString(“/sys/class/net/” +interfaceName + “/address”). toUpperCase()();} catch (IOException ex) {
return null;}*/}
* Get IP address from first non-localhost interface
* @param useIPv4 true=return ipv4, false=return ipv6
* @return address or empty string
public static String getIPAddress(boolean useIPv4) {
List addrs = (tInetAddresses());
for (InetAddress addr: addrs) {
if (! LoopbackAddress()) {
String sAddr = tHostAddress();
//boolean isIPv4 = IPv4Address(sAddr);
boolean isIPv4 = dexOf(‘:’)<0; if (useIPv4) { if (isIPv4) return sAddr;} else { if (! isIPv4) { int delim = dexOf('%'); // drop ip6 zone suffix return delim<0? UpperCase(): bstring(0, delim). toUpperCase();}}}}}} catch (Exception ignored) {} // for now eat exceptions return "";}} Disclaimer: Ideas and example code to this Utils class came from several SO posts and Google. I have cleaned and merged all examples. exploitr7831 gold badge13 silver badges24 bronze badges answered Oct 22 '12 at 8:12 WhomeWhome9, 7796 gold badges47 silver badges61 bronze badges 34 With permission ACCESS_WIFI_STATE declared in
One can use the WifiManager to obtain the IP address:
Context context = requireContext(). getApplicationContext();
WifiManager wm = (WifiManager) tSystemService(Context. WIFI_SERVICE);
String ip = rmatIpAddress(tConnectionInfo(). getIpAddress());
answered May 20 ’11 at 12:35
Nilesh TupeNilesh Tupe7, 2115 gold badges23 silver badges30 bronze badges
17
public static String getLocalIpAddress() {
for (Enumeration en = tNetworkInterfaces(); en. hasMoreElements();) {
NetworkInterface intf = xtElement();
for (Enumeration enumIpAddr = tInetAddresses(); enumIpAddr. hasMoreElements();) {
InetAddress inetAddress = xtElement();
if (! LoopbackAddress() && inetAddress instanceof Inet4Address) {
return tHostAddress();}}}} catch (SocketException ex) {
intStackTrace();}
return null;}
I’ve added inetAddress instanceof Inet4Address to check if it is a ipv4 address.
biegleux13k11 gold badges42 silver badges52 bronze badges
answered Sep 16 ’12 at 17:35
5
I used following code:
The reason I used hashCode was because I was getting some garbage values appended to the ip address when I used getHostAddress. But hashCode worked really well for me as then I can use Formatter to get the ip address with correct formatting.
Here is the example output:
getHostAddress: ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0
hashCode and Formatter: ***** IP=238. 194. 77. 212
As you can see 2nd methods gives me exactly what I need.
public String getLocalIpAddress() {
String ip = rmatIpAddress(inetAddress. hashCode());
Log. i(TAG, “***** IP=”+ ip);
return ip;}}}} catch (SocketException ex) {
Log. e(TAG, String());}
answered Apr 17 ’12 at 21:31
anargundanargund3, 2092 gold badges19 silver badges23 bronze badges
9
Though there’s a correct answer, I share my answer here and hope that this way will more convenience.
WifiManager wifiMan = (WifiManager) tSystemService(Context. WIFI_SERVICE);
WifiInfo wifiInf = tConnectionInfo();
int ipAddress = tIpAddress();
String ip = (“%d. %d. %d”, (ipAddress & 0xff), (ipAddress >> 8 & 0xff), (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
answered Aug 26 ’13 at 4:57
CYBCYB1, 03614 silver badges36 bronze badges
4
Below code might help you.. Don’t forget to add permissions..
public String getLocalIpAddress(){
for (Enumeration en = tNetworkInterfaces();
en. hasMoreElements();) {
return tHostAddress();}}}} catch (Exception ex) {
Log. e(“IP Address”, String());}
Add below permission in the manifest file.
happy coding!!
answered Jul 11 ’12 at 12:29
SatyamSatyam1, 5423 gold badges19 silver badges34 bronze badges
kotlin minimalist version
fun getIpv4HostAddress(): String {
tNetworkInterfaces()? ()? { networkInterface ->
etAddresses? ()? {! LoopbackAddress && it is Inet4Address}? { return Address}}
return “”}
answered Oct 11 ’19 at 20:53
Raphael CRaphael C1, 8661 gold badge18 silver badges18 bronze badges
private InetAddress getLocalAddress()throws IOException {
//return tHostAddress(). toString();
return inetAddress;}}}} catch (SocketException ex) {
Log. e(“SALMAN”, String());}
Azhar19. 5k38 gold badges134 silver badges205 bronze badges
answered Oct 26 ’11 at 6:14
salman khalidsalman khalid4, 6444 gold badges24 silver badges32 bronze badges
1
Method getDeviceIpAddress returns device’s ip address and prefers wifi interface address if it connected.
@NonNull
private String getDeviceIpAddress() {
String actualConnectedToNetwork = null;
ConnectivityManager connManager = (ConnectivityManager) getSystemService(NNECTIVITY_SERVICE);
if (connManager! = null) {
NetworkInfo mWifi = tNetworkInfo(ConnectivityManager. TYPE_WIFI);
if (Connected()) {
actualConnectedToNetwork = getWifiIp();}}
if (Empty(actualConnectedToNetwork)) {
actualConnectedToNetwork = getNetworkInterfaceIpAddress();}
actualConnectedToNetwork = “127. 0. 1”;}
return actualConnectedToNetwork;}
@Nullable
private String getWifiIp() {
final WifiManager mWifiManager = (WifiManager) getApplicationContext(). getSystemService(Context. WIFI_SERVICE);
if (mWifiManager! = null && WifiEnabled()) {
int ip = tConnectionInfo(). getIpAddress();
return (ip & 0xFF) + “. ” + ((ip >> 8) & 0xFF) + “. ” + ((ip >> 16) & 0xFF) + “. ”
+ ((ip >> 24) & 0xFF);}
public String getNetworkInterfaceIpAddress() {
NetworkInterface networkInterface = xtElement();
String host = tHostAddress();
if (! Empty(host)) {
return host;}}}}} catch (Exception ex) {
Log. e(“IP Address”, “getLocalIpAddress”, ex);}
answered Oct 12 ’17 at 13:40
In your activity, the following function getIpAddress(context) returns the phone’s IP address:
public static String getIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) tApplicationContext(). getSystemService(WIFI_SERVICE);
String ipAddress = intToInetAddress(tDhcpInfo(). ipAddress). toString();
ipAddress = bstring(1);
return ipAddress;}
public static InetAddress intToInetAddress(int hostAddress) {
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24))};
return tByAddress(addressBytes);} catch (UnknownHostException e) {
throw new AssertionError();}}
answered Jan 29 ’19 at 8:52
matdevmatdev3, 4724 gold badges26 silver badges44 bronze badges
This is a rework of this answer which strips out irrelevant information, adds helpful comments, names variables more clearly, and improves the logic.
Don’t forget to include the following permissions:
public class InternetHelper {
*
List interfaces =
(tNetworkInterfaces());
for (NetworkInterface interface_: interfaces) {
for (InetAddress inetAddress:
(tInetAddresses())) {
/* a loopback address would be something like 127. 1 (the device
itself). we want to return the first non-loopback address. */
String ipAddr = tHostAddress();
boolean isIPv4 = dexOf(‘:’) < 0; if (isIPv4 &&! useIPv4) { continue;} if (useIPv4 &&! isIPv4) { ipAddr = delim < 0? UpperCase(): bstring(0, delim). toUpperCase();} return ipAddr;}}}} catch (Exception ignored) {} // if we can't connect, just return empty string return "";} * Get IPv4 address from first non-localhost interface public static String getIPAddress() { return getIPAddress(true);}} answered Jul 12 '18 at 17:27 Jon McClungJon McClung1, 47817 silver badges26 bronze badges 0 WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); String ipAddress = lueOf(tDhcpInfo(). netmask). toString(); answered May 12 '15 at 20:31 mridulmridul1, 8369 gold badges27 silver badges48 bronze badges Recently, an IP address is still returned by getLocalIpAddress() despite being disconnected from the network (no service indicator). It means the IP address displayed in the Settings> About phone> Status was different from what the application thought.
I have implemented a workaround by adding this code before:
ConnectivityManager cm = getConnectivityManager();
NetworkInfo net = tActiveNetworkInfo();
if ((null == net) ||! ConnectedOrConnecting()) {
Does that ring a bell to anyone?
answered Nov 28 ’12 at 11:16
slash33slash3387911 silver badges17 bronze badges
Simply use Volley to get the ip from this site
RequestQueue queue = wRequestQueue(this);
String urlip = “;
StringRequest stringRequest = new StringRequest(, urlip, new stener() {
@Override
public void onResponse(String response) {
tText(response);}}, new rorListener() {
public void onErrorResponse(VolleyError error) {
tText(“didnt work”);}});
(stringRequest);
answered Aug 14 ’18 at 11:56
in Kotlin, without Formatter
private fun getIPAddress(useIPv4: Boolean): String {
var interfaces = (tNetworkInterfaces())
for (intf in interfaces) {
var addrs = (tInetAddresses());
for (addr in addrs) {
var sAddr = tHostAddress();
var isIPv4: Boolean
isIPv4 = dexOf(‘:’)<0 var delim = dexOf('%') // drop ip6 zone suffix if (delim < 0) { return UpperCase()} else { return bstring(0, delim). toUpperCase()}}}}}}} catch (e:) {} answered Dec 7 '18 at 16:03 zeinazeina412 bronze badges A device might have several IP addresses, and the one in use in a particular app might not be the IP that servers receiving the request will see. Indeed, some users use a VPN or a proxy such as Cloudflare Warp. If your purpose is to get the IP address as shown by servers that receive requests from your device, then the best is to query an IP geolocation service such as Ipregistry (disclaimer: I work for the company) with its Java client: IpregistryClient client = new IpregistryClient("tryout"); RequesterIpInfo requesterIpInfo = (); (); In addition to being really simple to use, you get additional information such as country, language, currency, the time zone for the device IP and you can identify whether the user is using a proxy. answered Feb 5 '20 at 17:29 LaurentLaurent13. 3k13 gold badges48 silver badges77 bronze badges This is the easiest and simple way ever exist on the internet... First of all, add this permission to your manifest file... "INTERNET" "ACCESS_NETWORK_STATE" add this in onCreate file of Activity.. getPublicIP(); Now Add this function to your private void getPublicIP() { ArrayList urls=new ArrayList(); //to read each line
new Thread(new Runnable(){
public void run(){
//TextView t; //to show the result, please declare and find it inside onCreate()
// Create a URL for the desired page
URL url = new URL(“); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) Connection();
tConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(tInputStream()));
//t=(TextView)findViewById(); // ideally do this in onCreate()
String str;
while ((str = adLine())! = null) {
(str);}
();} catch (Exception e) {
Log. d(“MyTag”, String());}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
(new Runnable(){
keText(, “Public IP:”(0), Toast. LENGTH_SHORT)();}
catch (Exception e){
keText(, “TurnOn wiffi to get public ip”, Toast. LENGTH_SHORT)();}}});}})();}
answered Feb 28 ’20 at 8:54
ZiaZia5094 silver badges10 bronze badges
3
public static String getdeviceIpAddress() {
answered Aug 24 at 15:12
Here is kotlin version of @Nilesh and @anargund
fun getIpAddress(): String {
var ip = “”
val wm = tSystemService(WIFI_SERVICE) as WifiManager
ip = rmatIpAddress(nnectionInfo. ipAddress)} catch (e:) {}
if (Empty()) {
val en = tNetworkInterfaces()
while (en. hasMoreElements()) {
val networkInterface = xtElement()
val enumIpAddr = etAddresses
while (enumIpAddr. hasMoreElements()) {
val inetAddress = xtElement()
if (! LoopbackAddress && inetAddress is Inet4Address) {
val host = tHostAddress()
if (NotEmpty()) {
ip = host
break;}}}}} catch (e:) {}}
if (Empty())
ip = “127. 1”
return ip}
answered Nov 27 ’18 at 8:08
SumitSumit85010 silver badges18 bronze badges
Compiling some of the ideas to get the wifi ip from the WifiManager in a nicer kotlin solution:
private fun getWifiIp(context: Context): String? {
return tSystemService() {
when {
it == null -> “No wifi available”! WifiEnabled -> “Wifi is disabled”
nnectionInfo == null -> “Wifi not connected”
else -> {
val ip = nnectionInfo. ipAddress
((ip and 0xFF). toString() + “. ” + (ip shr 8 and 0xFF) + “. ” + (ip shr 16 and 0xFF) + “. ” + (ip shr 24 and 0xFF))}}}}
Alternatively you can get the ip adresses of ip4 loopback devices via the NetworkInterface:
fun getNetworkIp4LoopbackIps(): Map = try {
tNetworkInterfaces(). asSequence(). associate { it. displayName to it. ip4LoopbackIps()}. filterValues { NotEmpty()}} catch (ex: Exception) {
emptyMap()}
private fun NetworkInterface. ip4LoopbackIps() =
Sequence()
{! LoopbackAddress && it is Inet4Address}
{ Address}
{ NotEmpty()}. joinToString()
answered Mar 6 ’20 at 9:40
MoritzMoritz9, 6417 gold badges45 silver badges57 bronze badges
If you have a shell; ifconfig eth0 worked for x86 device too
answered Dec 5 ’11 at 9:27
RzRRzR2, 90927 silver badges25 bronze badges
Please check this this code. we will get ip from mobile internet…
return tHostAddress(). toString();}}}
answered May 11 ’16 at 12:20
venkatvenkat1473 silver badges15 bronze badges
I don’t do Android, but I’d tackle this in a totally different way.
Send a query to Google, something like:
And refer to the HTML field where the response is posted. You may also query directly to the source.
Google will most like be there for longer than your Application.
Just remember, it could be that your user does not have internet at this time, what would you like to happen!
Good Luck
answered Jun 8 ’16 at 8:23
MakabMakab424 bronze badges
You can do this
String stringUrl = “;
//String stringUrl = “;
// Instantiate the RequestQueue.
RequestQueue queue = wRequestQueue(stance);
//String url =”;
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(, stringUrl,
new stener() {
// Display the first 500 characters of the response string.
Log. e(MGLogTag, “GET IP: ” + response);}}, new rorListener() {
IP = “That didn’t work! “;}});
// Add the request to the RequestQueue.
Pang8, 813144 gold badges81 silver badges115 bronze badges
answered Jul 25 ’18 at 3:02
// @NonNull
if (Empty(deviceIpAddress))
new PublicIPAddress(). execute();
return deviceIpAddress;}
public static String deviceIpAddress = “”;
public static class PublicIPAddress extends AsyncTask {
InetAddress localhost = null;
protected String doInBackground(String… urls) {
localhost = tLocalHost();
URL url_name = new URL(“);
BufferedReader sc = new BufferedReader(new InputStreamReader(Stream()));
deviceIpAddress = adLine()();} catch (Exception e) {
deviceIpAddress = “”;}
protected void onPostExecute(String string) {
Lg. d(“deviceIpAddress”, string);}}
answered Jan 25 ’19 at 11:23
In all honesty I am only a little familiar with code safety, so this may be hack-ish. But for me this is the most versatile way to do it:
package;
import;
public class MyIpByHost
{
public static void main(String a[])
try
InetAddress host = tByName(“nameOfDevice or webAddress”);
(tHostAddress());}
catch (UnknownHostException e)
intStackTrace();}}}
answered Oct 16 ’19 at 16:11
Based on what I have tested this is my proposal
public class hostUtil
public static String HOST_NAME = null;
public static String HOST_IPADDRESS = null;
public static String getThisHostName ()
if (HOST_NAME == null) obtainHostInfo ();
return HOST_NAME;}
public static String getThisIpAddress ()
if (HOST_IPADDRESS == null) obtainHostInfo ();
return HOST_IPADDRESS;}
protected static void obtainHostInfo ()
HOST_IPADDRESS = “127. 1”;
HOST_NAME = “localhost”;
InetAddress primera = tLocalHost();
String hostname = tLocalHost(). getHostName ();
if (! LoopbackAddress () &&! hostname. equalsIgnoreCase (“localhost”) &&
tHostAddress (). indexOf (‘:’) == -1)
// Got it without delay!!
HOST_IPADDRESS = tHostAddress ();
HOST_NAME = hostname;
// (“First try! ” + HOST_NAME + ” IP ” + HOST_IPADDRESS);
return;}
for (Enumeration netArr = tNetworkInterfaces(); netArr. hasMoreElements();)
NetworkInterface netInte = xtElement ();
for (Enumeration addArr = tInetAddresses (); addArr. hasMoreElements ();)
InetAddress laAdd = xtElement ();
String ipstring = tHostAddress ();
String hostName = tHostName ();
if (LoopbackAddress()) continue;
if (hostName. equalsIgnoreCase (“localhost”)) continue;
if (dexOf (‘:’) >= 0) continue;
HOST_IPADDRESS = ipstring;
HOST_NAME = hostName;
break;}}} catch (Exception ex) {}}}
answered Nov 29 ’15 at 16:31
elxalaelxala2512 silver badges5 bronze badges
Not the answer you’re looking for? Browse other questions tagged android ip-address or ask your own question.
Get IP Address of your device in Android Studio - Free Education

Get IP Address of your device in Android Studio – Free Education

Welcome. In this tutorial you will learn how to get our Device’s IP address in any Android Phone or Tablet.
Example to get IP Address in Android Studio
You might have seen that in many android applications our IP Address is shown automatically. Many VPN apps use this feature to tell their users that their IP is not secured. If you also want to use this feature in your android application then you will have to just use the code snippet given below:-
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);String ipAddress = rmatIpAddress(tConnectionInfo(). getIpAddress());tText(“Your Device IP Address: ” + ipAddress);
For this purpose we will have to use the WifiManager class which will allow us to manage all wifi connectivity related settings. The WIFI_SERVICE is used with getSystemService to retrive a wifimanager for handling management of wifi access. The function getConnectionInfo() is also used to return dynamic information about the current Wi-Fi connection, but only if there is any active connection. We have also used Formatter tool here to format the received data from wifiManager and extract our desired IP address.
The above code stated here will get the current IP address and will display it as a text in the text view. You can use this code as required in any part of your Android app.
Also note that the above code will require Internet so you will have to first modify the AndroidManifests file and add the following code to it.

The image below shows an example where the IP address of my current device was shown.
The Complete Code Snippet for above example is given below:-
Java ()
1234567891011121314151617181920
import;import;import;import;import;public class DisplayIPAddress extends AppCompatActivity { TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super. onCreate(savedInstanceState); setContentView(); textView = (TextView) findViewById(); WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); String ipAddress = rmatIpAddress(tConnectionInfo(). getIpAddress()); tText(“Your Device IP Address: ” + ipAddress);}}
XML ()
123456789101112131415161718192021

You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project.
For a more detailed guide, you can also visit android’s official guide below:-
Comment down below if you are facing any problems.
Also Read:-
Button Code Example for Android Studio
Check internet Example for Android Studio
Android get public ip address programmatically - Legend Blogs

Android get public ip address programmatically – Legend Blogs

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 how do I get the IP address of android device 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”.
Public methods
Resource: Network Interface
booleanequals(Object obj)Compares this object against the specified NetworkInterfacegetByIndex(int index)Get a network interface given its NetworkInterfacegetByInetAddress(InetAddress addr)Convenience method to search for a network interface that has the specified Internet Protocol (IP) address bound to NetworkInterfacegetByName(String name)Searches for the network interface with the specified ringgetDisplayName()Get the display name of this network []getHardwareAddress()Returns the hardware address (usually MAC) of the interface if it has one and if it can be accessed given the current tgetIndex()Returns the index of this network interface. EnumerationgetInetAddresses()Convenience method to return an Enumeration with all or a subset of the InetAddresses bound to this network getInterfaceAddresses()Get a List of all or a subset of the InterfaceAddresses of this network tgetMTU()Returns the Maximum Transmission Unit (MTU) of this ringgetName()Get the name of this network EnumerationgetNetworkInterfaces()Returns all the interfaces on this tworkInterfacegetParent()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. EnumerationgetSubInterfaces()Get an Enumeration with all the subinterfaces (also known as virtual interfaces) attached to this network oleanisLoopback()Returns whether a network interface is a loopback oleanisPointToPoint()Returns whether a network interface is a point to point oleanisUp()Returns whether a network interface is up and oleanisVirtual()Returns whether this interface is a virtual interface (also called subinterface). booleansupportsMulticast()Returns whether a network interface supports multicasting or not.
Get the 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/
Android Collapsing Toolbar With Image




Step 3
Add the following code to











Step 4
Add the following code to src/
import;
public class MainActivity extends AppCompatActivity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super. onCreate(savedInstanceState);
setContentView();
textView = findViewById();
tText(“Your Device IP Address: ” + getIPAddress(true));}
public static String getIPAddress(boolean useIPv4) {
try {
List interfaces = (tNetworkInterfaces());
for (NetworkInterface intf: interfaces) {
List addrs = (tInetAddresses());
for (InetAddress addr: addrs) {
if (! LoopbackAddress()) {
String sAddr = tHostAddress(). toUpperCase();
boolean isIPv4 = IPv4Address(sAddr);
if (useIPv4) {
if (isIPv4)
return sAddr;} else {
if (! isIPv4) {
int delim = dexOf(‘%’); // drop ip6 port suffix
return delim<0? sAddr: bstring(0, delim);}}}}}} catch (Exception e) { intStackTrace();} return "";}}

Frequently Asked Questions about android studio ip address

How do I find the IP address of my Android studio?

Example to get IP Address in Android StudioWifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);String ipAddress = Formatter. formatIpAddress(wifiManager. getConnectionInfo(). getIpAddress() );textView. setText(“Your Device IP Address: ” + ipAddress);Jul 7, 2019

How do I find the IP address of my Android phone programmatically?

Get the IP address of android device programmaticallyCreate a new project in Android Studio, go to File -> New Project and fill all required details to create a new project.Add the following code to res/layout/activity_main. … Add the following code to androidManifest.xml <?More items…•Aug 29, 2020

Leave a Reply

Your email address will not be published. Required fields are marked *