Is it possible to get the IP address of the device using some code?
With permission ACCESS_WIFI_STATE
declared in AndroidManifest.xml
:
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"/>
One can use the WifiManager
to obtain the IP address:
Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
getHostAddress()
, which supports both IPv4 and IPv6 addresses. This method does not support IPv6 addresses. –
Ambrotype getApplicationContext().getSystemService(WIFI_SERVICE)
–
Frogmouth 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.
// AndroidManifest.xml permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
// test functions
Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6
Utils.java
import java.io.*;
import java.net.*;
import java.util.*;
//import org.apache.http.conn.util.InetAddressUtils;
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 < bytes.length; idx++) {
int intVal = bytes[idx] & 0xff;
if (intVal < 0x10) sbuf.append("0");
sbuf.append(Integer.toHexString(intVal).toUpperCase());
}
return sbuf.toString();
}
/**
* 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 str.getBytes("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 java.io.IOException if error occurs
*/
public static String loadFileAsString(String filename) throws java.io.IOException {
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((read=is.read(bytes)) != -1) {
if (count==0 && bytes[0]==(byte)0xEF && bytes[1]==(byte)0xBB && bytes[2]==(byte)0xBF ) {
isUTF8=true;
baos.write(bytes, 3, read-3); // drop UTF8 bom marker
} else {
baos.write(bytes, 0, read);
}
count+=read;
}
return isUTF8 ? new String(baos.toByteArray(), "UTF-8") : new String(baos.toByteArray());
} finally {
try{ is.close(); } 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) {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
if (interfaceName != null) {
if (!intf.getName().equalsIgnoreCase(interfaceName)) continue;
}
byte[] mac = intf.getHardwareAddress();
if (mac==null) return "";
StringBuilder buf = new StringBuilder();
for (byte aMac : mac) buf.append(String.format("%02X:",aMac));
if (buf.length()>0) buf.deleteCharAt(buf.length()-1);
return buf.toString();
}
} catch (Exception ignored) { } // for now eat exceptions
return "";
/*try {
// this is so Linux hack
return loadFileAsString("/sys/class/net/" +interfaceName + "/address").toUpperCase().trim();
} 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) {
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();
//boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
boolean isIPv4 = sAddr.indexOf(':')<0;
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
int delim = sAddr.indexOf('%'); // drop ip6 zone suffix
return delim<0 ? sAddr.toUpperCase() : sAddr.substring(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.
toUpperCase()
. Catching Exception
is always dodgy (and helper methods should throw anyway and let the caller deal with the Exception - did not amend this though). Formatting : should be no more than 80 lines. Conditional execution for getHardwareAddress()
- patch : github.com/Utumno/AndroidHelpers/commit/…. What you say ? –
Araucaria toUpperCase()
? –
Phaedrus getMACAddress(null)
and see what's returned. Debug print all interface names to see what your device is using. Modify that same method to print out to a logcat. –
Chelonian getMACAddress(null)
is using the first interface found. You may need to printout all interface names to see your device naming. –
Chelonian getMACAddress(null)
to use first interface. Also print out all available interface names. Or do you mean getIPAddress(true)
IP getter is empty? –
Chelonian getIPAddress(true)
method, the return value always empty. –
Carder getIPAddress(false)
to get ipv6 also empty? Then I don't know what is, you should print out an exception if that is to happen, example function silently eats EX. Final reason is to have only a localhost interface, I guess you need to add logcat debug calls to a getter function. –
Chelonian With permission ACCESS_WIFI_STATE
declared in AndroidManifest.xml
:
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"/>
One can use the WifiManager
to obtain the IP address:
Context context = requireContext().getApplicationContext();
WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
getHostAddress()
, which supports both IPv4 and IPv6 addresses. This method does not support IPv6 addresses. –
Ambrotype getApplicationContext().getSystemService(WIFI_SERVICE)
–
Frogmouth public static 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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
I've added inetAddress
instanceof Inet4Address
to check if it is a ipv4 address.
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 :
1.using getHostAddress
: ***** IP=fe80::65ca:a13d:ea5a:233d%rmnet_sdio0
2.using hashCode
and Formatter
: ***** IP=238.194.77.212
As you can see 2nd methods gives me exactly what I need.
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 = Formatter.formatIpAddress(inetAddress.hashCode());
Log.i(TAG, "***** IP="+ ip);
return ip;
}
}
}
} catch (SocketException ex) {
Log.e(TAG, ex.toString());
}
return null;
}
getHostAddress()
will do the same as the formatter stuff you added. –
Struble Though there's a correct answer, I share my answer here and hope that this way will more convenience.
WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
int ipAddress = wifiInf.getIpAddress();
String ip = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
–
Grieco Below code might help you.. Don't forget to add permissions..
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()) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Add below permission in the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
happy coding!!
kotlin minimalist version
fun getIpv4HostAddress(): String {
NetworkInterface.getNetworkInterfaces()?.toList()?.map { networkInterface ->
networkInterface.inetAddresses?.toList()?.find {
!it.isLoopbackAddress && it is Inet4Address
}?.let { return it.hostAddress }
}
return ""
}
You do not need to add permissions like what is the case with the solutions provided so far. Download this website as a string:
or
Downloading a website as a string can be done with java code:
http://www.itcuties.com/java/read-url-to-string/
Parse the JSON object like this:
https://mcmap.net/q/11375/-how-to-parse-json-in-java
The json attribute "query" or "ip" contains the IP address.
private InetAddress getLocalAddress()throws IOException {
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()) {
//return inetAddress.getHostAddress().toString();
return inetAddress;
}
}
}
} catch (SocketException ex) {
Log.e("SALMAN", ex.toString());
}
return null;
}
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(Context.CONNECTIVITY_SERVICE);
if (connManager != null) {
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
actualConnectedToNetwork = getWifiIp();
}
}
if (TextUtils.isEmpty(actualConnectedToNetwork)) {
actualConnectedToNetwork = getNetworkInterfaceIpAddress();
}
if (TextUtils.isEmpty(actualConnectedToNetwork)) {
actualConnectedToNetwork = "127.0.0.1";
}
return actualConnectedToNetwork;
}
@Nullable
private String getWifiIp() {
final WifiManager mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (mWifiManager != null && mWifiManager.isWifiEnabled()) {
int ip = mWifiManager.getConnectionInfo().getIpAddress();
return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "."
+ ((ip >> 24) & 0xFF);
}
return null;
}
@Nullable
public String getNetworkInterfaceIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface networkInterface = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
String host = inetAddress.getHostAddress();
if (!TextUtils.isEmpty(host)) {
return host;
}
}
}
}
} catch (Exception ex) {
Log.e("IP Address", "getLocalIpAddress", ex);
}
return null;
}
You can use LinkProperties. It's recommended for new Android versions.
This function retrieves local IP address for both WiFi and Mobile Data. It requires Manifest.permission.ACCESS_NETWORK_STATE
permission.
@Nullable
public static String getDeviceIpAddress(@NonNull ConnectivityManager connectivityManager) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork());
InetAddress inetAddress;
for(LinkAddress linkAddress : linkProperties.getLinkAddresses()) {
inetAddress = linkAddress.getAddress();
if (inetAddress instanceof Inet4Address
&& !inetAddress.isLoopbackAddress()
&& inetAddress.isSiteLocalAddress()) {
return inetAddress.getHostAddress();
}
}
return null;
}
In your activity, the following function getIpAddress(context)
returns the phone's IP address:
public static String getIpAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getApplicationContext()
.getSystemService(WIFI_SERVICE);
String ipAddress = intToInetAddress(wifiManager.getDhcpInfo().ipAddress).toString();
ipAddress = ipAddress.substring(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)) };
try {
return InetAddress.getByAddress(addressBytes);
} catch (UnknownHostException e) {
throw new AssertionError();
}
}
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:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
InternetHelper.java:
public class InternetHelper {
/**
* 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) {
try {
List<NetworkInterface> interfaces =
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface interface_ : interfaces) {
for (InetAddress inetAddress :
Collections.list(interface_.getInetAddresses())) {
/* a loopback address would be something like 127.0.0.1 (the device
itself). we want to return the first non-loopback address. */
if (!inetAddress.isLoopbackAddress()) {
String ipAddr = inetAddress.getHostAddress();
boolean isIPv4 = ipAddr.indexOf(':') < 0;
if (isIPv4 && !useIPv4) {
continue;
}
if (useIPv4 && !isIPv4) {
int delim = ipAddr.indexOf('%'); // drop ip6 zone suffix
ipAddr = delim < 0 ? ipAddr.toUpperCase() :
ipAddr.substring(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
*
* @return address or empty string
*/
public static String getIPAddress() {
return getIPAddress(true);
}
}
public static String getdeviceIpAddress() {
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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ipAddress = BigInteger.valueOf(wm.getDhcpInfo().netmask).toString();
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 = cm.getActiveNetworkInfo();
if ((null == net) || !net.isConnectedOrConnecting()) {
return null;
}
Does that ring a bell to anyone?
Simply use Volley to get the ip from this site
RequestQueue queue = Volley.newRequestQueue(this);
String urlip = "http://checkip.amazonaws.com/";
StringRequest stringRequest = new StringRequest(Request.Method.GET, urlip, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
txtIP.setText(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
txtIP.setText("didnt work");
}
});
queue.add(stringRequest);
in Kotlin, without Formatter
private fun getIPAddress(useIPv4 : Boolean): String {
try {
var interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
for (intf in interfaces) {
var addrs = Collections.list(intf.getInetAddresses());
for (addr in addrs) {
if (!addr.isLoopbackAddress()) {
var sAddr = addr.getHostAddress();
var isIPv4: Boolean
isIPv4 = sAddr.indexOf(':')<0
if (useIPv4) {
if (isIPv4)
return sAddr;
} else {
if (!isIPv4) {
var delim = sAddr.indexOf('%') // drop ip6 zone suffix
if (delim < 0) {
return sAddr.toUpperCase()
}
else {
return sAddr.substring(0, delim).toUpperCase()
}
}
}
}
}
}
} catch (e: java.lang.Exception) { }
return ""
}
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:
https://github.com/ipregistry/ipregistry-java
IpregistryClient client = new IpregistryClient("tryout");
RequesterIpInfo requesterIpInfo = client.lookup();
requesterIpInfo.getIp();
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.
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 MainActivity.class.
private void getPublicIP() {
ArrayList<String> urls=new ArrayList<String>(); //to read each line
new Thread(new Runnable(){
public void run(){
//TextView t; //to show the result, please declare and find it inside onCreate()
try {
// Create a URL for the desired page
URL url = new URL("https://api.ipify.org/"); //My text file location
//First open the connection
HttpURLConnection conn=(HttpURLConnection) url.openConnection();
conn.setConnectTimeout(60000); // timing out in a minute
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()
String str;
while ((str = in.readLine()) != null) {
urls.add(str);
}
in.close();
} catch (Exception e) {
Log.d("MyTag",e.toString());
}
//since we are in background thread, to post results we have to go back to ui thread. do the following for that
PermissionsActivity.this.runOnUiThread(new Runnable(){
public void run(){
try {
Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();
}
catch (Exception e){
Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();
}
}
});
}
}).start();
}
Here is kotlin version of @Nilesh and @anargund
fun getIpAddress(): String {
var ip = ""
try {
val wm = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
ip = Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
} catch (e: java.lang.Exception) {
}
if (ip.isEmpty()) {
try {
val en = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val networkInterface = en.nextElement()
val enumIpAddr = networkInterface.inetAddresses
while (enumIpAddr.hasMoreElements()) {
val inetAddress = enumIpAddr.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
val host = inetAddress.getHostAddress()
if (host.isNotEmpty()) {
ip = host
break;
}
}
}
}
} catch (e: java.lang.Exception) {
}
}
if (ip.isEmpty())
ip = "127.0.0.1"
return ip
}
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 context.getSystemService<WifiManager>().let {
when {
it == null -> "No wifi available"
!it.isWifiEnabled -> "Wifi is disabled"
it.connectionInfo == null -> "Wifi not connected"
else -> {
val ip = it.connectionInfo.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<String, String> = try {
NetworkInterface.getNetworkInterfaces()
.asSequence()
.associate { it.displayName to it.ip4LoopbackIps() }
.filterValues { it.isNotEmpty() }
} catch (ex: Exception) {
emptyMap()
}
private fun NetworkInterface.ip4LoopbackIps() =
inetAddresses.asSequence()
.filter { !it.isLoopbackAddress && it is Inet4Address }
.map { it.hostAddress }
.filter { it.isNotEmpty() }
.joinToString()
Blockquote // get Device Ip Address
open fun getLocalIpAddress(): String? {
try {
val en: Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
while (en.hasMoreElements()) {
val networkInterface: NetworkInterface = en.nextElement()
val enumerationIpAddress: Enumeration<InetAddress> = networkInterface.inetAddresses
while (enumerationIpAddress.hasMoreElements()) {
val inetAddress: InetAddress = enumerationIpAddress.nextElement()
if (!inetAddress.isLoopbackAddress && inetAddress is Inet4Address) {
return inetAddress.getHostAddress()
}
}
}
} catch (ex: SocketException) {
ex.printStackTrace()
}
return null
}
If you have a shell ; ifconfig eth0 worked for x86 device too
Please check this code...Using this code. we will get ip from mobile internet...
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()) {
return inetAddress.getHostAddress().toString();
}
}
}
I don't do Android, but I'd tackle this in a totally different way.
Send a query to Google, something like: https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=my%20ip
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
You can do this
String stringUrl = "https://ipinfo.io/ip";
//String stringUrl = "http://whatismyip.akamai.com/";
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.instance);
//String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, stringUrl,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
Log.e(MGLogTag, "GET IP : " + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
IP = "That didn't work!";
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
// @NonNull
public static String getIPAddress() {
if (TextUtils.isEmpty(deviceIpAddress))
new PublicIPAddress().execute();
return deviceIpAddress;
}
public static String deviceIpAddress = "";
public static class PublicIPAddress extends AsyncTask<String, Void, String> {
InetAddress localhost = null;
protected String doInBackground(String... urls) {
try {
localhost = InetAddress.getLocalHost();
URL url_name = new URL("http://bot.whatismyipaddress.com");
BufferedReader sc = new BufferedReader(new InputStreamReader(url_name.openStream()));
deviceIpAddress = sc.readLine().trim();
} catch (Exception e) {
deviceIpAddress = "";
}
return deviceIpAddress;
}
protected void onPostExecute(String string) {
Lg.d("deviceIpAddress", string);
}
}
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 com.my_objects.ip;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MyIpByHost
{
public static void main(String a[])
{
try
{
InetAddress host = InetAddress.getByName("nameOfDevice or webAddress");
System.out.println(host.getHostAddress());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
} }
For kotlin language.
fun contextIP(context: Context): String {
val wm: WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
return Formatter.formatIpAddress(wm.connectionInfo.ipAddress)
}
This is the proper way of finding device ip address.
package com.oseamiya.deviceinformation;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.RouteInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import androidx.annotation.RequiresApi;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static android.content.Context.CONNECTIVITY_SERVICE;
public class NetworkInformation {
private Context context;
private static final String TAG = "NetworkInformation";
public NetworkInformation(Context context){
this.context = context;
}
/**
* Get the Ip address of the device.
* The first method doesn't require ACCESS_WIFI_STATE permission
* if exception is caught then it will implement other method
* @return ipAddress in String
*/
@SuppressLint("DefaultLocale")
public String getIpAddress(boolean useIPv4){
int delim = 0;
String finalAdress = "";
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for(NetworkInterface intf : interfaces){
List<InetAddress> addresses = Collections.list(intf.getInetAddresses());
for(InetAddress addr : addresses){
if(!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress();
boolean isIPv4 = sAddr.indexOf(':') < 0 ;
if(useIPv4){
if(isIPv4)
finalAdress = sAddr;
} else {
if(!isIPv4){
delim = sAddr.indexOf('%');
finalAdress = delim<0 ? sAddr.toUpperCase() : sAddr.substring(0 , delim);
}
}
}
}
}
} catch (SocketException e) {
e.printStackTrace();
WifiManager wifiManager = (WifiManager) this.context.getSystemService(Context.WIFI_SERVICE);
int ipAddress = wifiManager.getConnectionInfo().getIpAddress();
finalAdress = String.format("%d.%d.%d.%d", (ipAddress & 0xff),(ipAddress >> 8 & 0xff),(ipAddress >> 16 & 0xff),(ipAddress >> 24 & 0xff));
}
return finalAdress;
}
private static final String[] FACTORY_DNS_SERVERS = {
"8.8.8.8",
"8.8.4.4"
};
private static final String METHOD_EXEC_PROP_DELIM = "]: [";
/**
* To get all the DNS servers available(With all the methods)
* Got this code from https://mcmap.net/q/11378/-how-do-you-get-the-current-dns-servers-for-android
* Thanks to Grigore Madani for the codes :)
* @return arrays of DNS Servers
*/
public String [] getServers() {
String[] result;
result = getServersMethodSystemProperties();
if (result != null && result.length > 0) {
return result;
}
result = getServersMethodConnectivityManager();
if (result != null && result.length > 0) {
return result;
}
result = getServersMethodExec();
if (result != null && result.length > 0) {
return result;
}
return FACTORY_DNS_SERVERS;
}
private String [] getServersMethodConnectivityManager() {
// This code only works on LOLLIPOP and higher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
try {
ArrayList<String> priorityServersArrayList = new ArrayList<>();
ArrayList<String> serversArrayList = new ArrayList<>();
ConnectivityManager connectivityManager = (ConnectivityManager) this.context.getSystemService(CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
// Iterate all networks
// Notice that android LOLLIPOP or higher allow iterating multiple connected networks of SAME type
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.isConnected()) {
LinkProperties linkProperties = connectivityManager.getLinkProperties(network);
List<InetAddress> dnsServersList = linkProperties.getDnsServers();
// Prioritize the DNS servers for link which have a default route
if (linkPropertiesHasDefaultRoute(linkProperties)) {
for (InetAddress element: dnsServersList) {
String dnsHost = element.getHostAddress();
priorityServersArrayList.add(dnsHost);
}
} else {
for (InetAddress element: dnsServersList) {
String dnsHost = element.getHostAddress();
serversArrayList.add(dnsHost);
}
}
}
}
}
// Append secondary arrays only if priority is empty
if (priorityServersArrayList.isEmpty()) {
priorityServersArrayList.addAll(serversArrayList);
}
// Stop here if we have at least one DNS server
if (priorityServersArrayList.size() > 0) {
return priorityServersArrayList.toArray(new String[0]);
}
} catch (Exception ex) {
Log.d(TAG, "Exception detecting DNS servers using ConnectivityManager method", ex);
}
}
// Failure
return null;
}
private String [] getServersMethodSystemProperties() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// This originally looked for all lines containing .dns; but
// http://code.google.com/p/android/issues/detail?id=2207#c73
// indicates that net.dns* should always be the active nameservers, so
// we use those.
final String re1 = "^\\d+(\\.\\d+){3}$";
final String re2 = "^[0-9a-f]+(:[0-9a-f]*)+:[0-9a-f]+$";
ArrayList<String> serversArrayList = new ArrayList<>();
try {
@SuppressLint("PrivateApi") Class SystemProperties = Class.forName("android.os.SystemProperties");
Method method = SystemProperties.getMethod("get", new Class[]{String.class});
final String[] netdns = new String[]{"net.dns1", "net.dns2", "net.dns3", "net.dns4"};
for (int i = 0; i < netdns.length; i++) {
Object[] args = new Object[]{netdns[i]};
String v = (String) method.invoke(null, args);
if (v != null && (v.matches(re1) || v.matches(re2)) && !serversArrayList.contains(v)) {
serversArrayList.add(v);
}
}
// Stop here if we have at least one DNS server
if (serversArrayList.size() > 0) {
return serversArrayList.toArray(new String[0]);
}
} catch (Exception ex) {
Log.d(TAG, "Exception detecting DNS servers using SystemProperties method", ex);
}
}
// Failed
return null;
}
/**
* Detect android DNS servers by executing getprop string command in a separate process
*
* Notice there is an android bug when Runtime.exec() hangs without providing a Process object.
* This problem is fixed in Jelly Bean (Android 4.1) but not in ICS (4.0.4) and probably it will never be fixed in ICS.
* https://mcmap.net/q/11377/-runtime-exec-bug-hangs-without-providing-a-process-object/11362081
*
* @return Dns servers array
*/
private String [] getServersMethodExec() {
// We are on the safe side and avoid any bug
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
try {
Process process = Runtime.getRuntime().exec("getprop");
InputStream inputStream = process.getInputStream();
LineNumberReader lineNumberReader = new LineNumberReader(new InputStreamReader(inputStream));
Set<String> serversSet = methodExecParseProps(lineNumberReader);
if (serversSet != null && serversSet.size() > 0) {
return serversSet.toArray(new String[0]);
}
} catch (Exception ex) {
Log.d(TAG, "Exception in getServersMethodExec", ex);
}
}
// Failed
return null;
}
/**
* Parse properties produced by executing getprop command
* @param lineNumberReader
* @return Set of parsed properties
* @throws Exception
*/
private Set<String> methodExecParseProps(BufferedReader lineNumberReader) throws Exception {
String line;
Set<String> serversSet = new HashSet<String>(10);
while ((line = lineNumberReader.readLine()) != null) {
int split = line.indexOf(METHOD_EXEC_PROP_DELIM);
if (split == -1) {
continue;
}
String property = line.substring(1, split);
int valueStart = split + METHOD_EXEC_PROP_DELIM.length();
int valueEnd = line.length() - 1;
if (valueEnd < valueStart) {
// This can happen if a newline sneaks in as the first character of the property value. For example
// "[propName]: [\n…]".
Log.d(TAG, "Malformed property detected: \"" + line + '"');
continue;
}
String value = line.substring(valueStart, valueEnd);
if (value.isEmpty()) {
continue;
}
if (property.endsWith(".dns") || property.endsWith(".dns1") ||
property.endsWith(".dns2") || property.endsWith(".dns3") ||
property.endsWith(".dns4")) {
// normalize the address
InetAddress ip = InetAddress.getByName(value);
if (ip == null) continue;
value = ip.getHostAddress();
if (value == null) continue;
if (value.length() == 0) continue;
serversSet.add(value);
}
}
return serversSet;
}
/**
* Returns true if the specified link properties have any default route
* @param linkProperties
* @return true if the specified link properties have default route or false otherwise
*/
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean linkPropertiesHasDefaultRoute(LinkProperties linkProperties) {
for (RouteInfo route : linkProperties.getRoutes()) {
if (route.isDefaultRoute()) {
return true;
}
}
return false;
}
// New methods are added from here
/**
* @return whether adb debugging is enabled or not in boolean
*/
public boolean isADBDebuggingEnabled(){
return Settings.Secure.getInt(this.context.getContentResolver(), "adb_enabled" , 0) > 0 ;
}
@RequiresApi(api = Build.VERSION_CODES.M)
public boolean isVpnConnection(){
return Settings.Secure.getInt(this.context.getContentResolver(), "vpn_state", 0) == 1 || isvpn1() || isvpn2();
}
private boolean isvpn1() {
String iface = "";
try {
for (NetworkInterface networkInterface : Collections.list(NetworkInterface.getNetworkInterfaces())) {
if (networkInterface.isUp())
iface = networkInterface.getName();
Log.d("DEBUG", "IFACE NAME: " + iface);
if ( iface.contains("tun") || iface.contains("ppp") || iface.contains("pptp")) {
return true;
}
}
} catch (SocketException e1) {
e1.printStackTrace();
}
return false;
}
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isvpn2() {
ConnectivityManager cm = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network activeNetwork = cm.getActiveNetwork();
NetworkCapabilities caps = cm.getNetworkCapabilities(activeNetwork);
boolean vpnInUse = caps.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
return vpnInUse;
}
}
Based on what I have tested this is my proposal
import java.net.*;
import java.util.*;
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.0.0.1";
HOST_NAME = "localhost";
try
{
InetAddress primera = InetAddress.getLocalHost();
String hostname = InetAddress.getLocalHost().getHostName ();
if (!primera.isLoopbackAddress () &&
!hostname.equalsIgnoreCase ("localhost") &&
primera.getHostAddress ().indexOf (':') == -1)
{
// Got it without delay!!
HOST_IPADDRESS = primera.getHostAddress ();
HOST_NAME = hostname;
//System.out.println ("First try! " + HOST_NAME + " IP " + HOST_IPADDRESS);
return;
}
for (Enumeration<NetworkInterface> netArr = NetworkInterface.getNetworkInterfaces(); netArr.hasMoreElements();)
{
NetworkInterface netInte = netArr.nextElement ();
for (Enumeration<InetAddress> addArr = netInte.getInetAddresses (); addArr.hasMoreElements ();)
{
InetAddress laAdd = addArr.nextElement ();
String ipstring = laAdd.getHostAddress ();
String hostName = laAdd.getHostName ();
if (laAdd.isLoopbackAddress()) continue;
if (hostName.equalsIgnoreCase ("localhost")) continue;
if (ipstring.indexOf (':') >= 0) continue;
HOST_IPADDRESS = ipstring;
HOST_NAME = hostName;
break;
}
}
} catch (Exception ex) {}
}
}
© 2022 - 2024 — McMap. All rights reserved.