6

I want to retrieve publick IP Address, the address that we get for example from whatismyipaddress.com and I don't want to use any third party servcie https://www.ipify.org. Is there any way to fetch this IP address from inbuilt classes or library in Android.

If not possible to get the required data from Android libraries, please suggest any logic to get the same in server level instead of fetching in client level. Note: Loadbalancer is present before routing to actual web-application

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mahesh
  • 75
  • 1
  • 1
  • 6
  • 2
    Does this answer your question? [How to programmatically get a public IP address?](https://stackoverflow.com/questions/47812879/how-to-programmatically-get-a-public-ip-address) – Md. Asaduzzaman Jan 20 '20 at 07:50
  • Also check this: [How to get IP address of the device from code?](https://stackoverflow.com/questions/6064510/how-to-get-ip-address-of-the-device-from-code) – Md. Asaduzzaman Jan 20 '20 at 07:51
  • Thanks for the information, I've gone through the links, but I'm looking for logic without using any external webservices. – Mahesh Jan 20 '20 at 07:57

4 Answers4

12

I use this method in my project.. so you can use it.. It will return you device IP

private String getIpAddress() {
    String ip = "";
    try {
        Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (enumNetworkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
            Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
            while (enumInetAddress.hasMoreElements()) {
                InetAddress inetAddress = enumInetAddress.nextElement();

                if (inetAddress.isSiteLocalAddress()) {
                    ip += inetAddress.getHostAddress();
                }

            }

        }

    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        ip += "Something Wrong! " + e.toString() + "\n";
    }

    return ip;
}

If you want to get Public IP of Network that your device connected with use this code...

public class GetPublicIP extends AsyncTask<String, String, String>{

    @Override
    protected String doInBackground(String... strings) {
        String publicIP = "";
        try  {
            java.util.Scanner s = new java.util.Scanner(
                    new java.net.URL(
                            "https://api.ipify.org")
                            .openStream(), "UTF-8")
                    .useDelimiter("\\A");
            publicIP = s.next();
            System.out.println("My current IP address is " + publicIP);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }

        return publicIP;
    }

    @Override
    protected void onPostExecute(String publicIp) {
        super.onPostExecute(publicIp);

        Log.e("PublicIP", publicIp+"");
        //Here 'publicIp' is your desire public IP
    }
}

new execute it

new GetPublicIP().execute();
Md. Enamul Haque
  • 926
  • 8
  • 14
  • Thanks for the suggestion, the suggested logic is returning the device IP address, something like 100.81.*.* . But I'm looking for Public IP address. – Mahesh Jan 20 '20 at 09:09
  • Public address of what? Android Device? – Md. Enamul Haque Jan 20 '20 at 12:14
  • Public IP of network connection used by Android device, which usually get on whatismyipaddress.com, https://www.ipify.org, etc. My IP Address Is: IPv4: 223.*.*.* IPv6: Not detected My IP Information: ISP: Bharti Airtel City: Visakhapatnam Region: Andhra Pradesh Country: India – Mahesh Jan 20 '20 at 13:38
  • `100.0` certainly is a public range, too. Just disable mobile data and use the WiFi. – Martin Zeitler Jan 21 '20 at 04:37
  • I've meant @Mahesh ...likely there's two public IPs, hence it's two interfaces. And depending which interface is being used for the HTTP request, the results may vary (WiFi is being preferred over UMTS). – Martin Zeitler Jan 21 '20 at 04:48
  • Hi MartinZeitler you are right... But he wants may be service provider IP.. that can get by my second code... @Mashesh you can find your solution from second code that I update... feel free to ask if any problem... – Md. Enamul Haque Jan 23 '20 at 02:06
  • @Md.EnamulHaque Yes, I want Service provider IP. But, due to security concerns we can't use third party web services like ipify.org. My actual requirement is, server should get the service provider IP of each request for better audit and business requirements. Till now we are trying to get the IP details in client and sharing as parameter in the service call. If that is not possible, please suggest is this can be done in server side by using request headers or something else? – Mahesh Jan 23 '20 at 06:22
4

With kotlin and Coroutines,

private suspend fun getMyPublicIpAsync() : Deferred<String> =
        coroutineScope {
            async(Dispatchers.IO) {
                var result = ""
                result = try {
                    val url = URL("https://api.ipify.org")
                    val httpsURLConnection = url.openConnection()
                    val iStream = httpsURLConnection.getInputStream()
                    val buff = ByteArray(1024)
                    val read = iStream.read(buff)
                    String(buff,0, read)
                } catch (e: Exception) {
                    "error : $e"
                }
                return@async result
            }
        }


private fun myFunction() {
   CoroutineScope(Dispatchers.Main).launch {
      val myPublicIp = getMyPublicIpAsync().await()
      Toast.makeText(this@MainActivity, myPublicIp, Toast.LENGTH_LONG).show()
   }
}
1

Use this method in order to get your IpAddress

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 = sAddr.indexOf(':')<0;

                        if (useIPv4) {
                            if (isIPv4) 
                                return sAddr;
                        } else {
                            if (!isIPv4) {
                                int delim = sAddr.indexOf('%'); 
                                return delim<0 ? sAddr.toUpperCase() : sAddr.substring(0, delim).toUpperCase();
                            }
                        }
                    }
                }
            }
        } catch (Exception ignored) { } 
        return "";
    }
Ajeett
  • 814
  • 2
  • 7
  • 18
  • 1
    Thanks for the suggestion, the suggested logic is returning the private IP address, something like 192.168.*.* . But I'm looking for Public IP address. – Mahesh Jan 20 '20 at 09:09
  • @Mahesh here is the perfect solution https://medium.com/@ISKFaisal/android-get-public-ip-address-with-java-kotlin-4d0575d2847 – Faisal Shaikh Aug 05 '23 at 21:01
0

Get Public IP Address with Kotlin in Android

var ip: String? = null
val thread = Thread {
    try {
        val url = URL("https://api.ipify.org")
        val connection = url.openConnection()
        connection.setRequestProperty("User-Agent", "Mozilla/5.0") // Set a User-Agent to avoid HTTP 403 Forbidden error
        val inputStream = connection.getInputStream()
        val s = java.util.Scanner(inputStream, "UTF-8").useDelimiter("\\A")
        ip = s.next()
        inputStream.close()
    } catch (e: Exception) {
        e.printStackTrace()
    }
}
thread.start()

Get Public IP Address with Java in Android

String ip;
Thread thread = new Thread(() -> {
    try {
        URL url = new URL("https://api.ipify.org");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // Set a User-Agent to avoid HTTP 403 Forbidden error

        try (Scanner s = new Scanner(connection.getInputStream(), "UTF-8").useDelimiter("\\A")) {
            ip = s.next();
        }

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
});
thread.start();

I have explained each line on my medium post Android — Get Public IP Address with Java & Kotlin, if anyone interested can read from there.

Faisal Shaikh
  • 3,900
  • 5
  • 40
  • 77