2

Started working on a network monitoring app and I was wondering if there was a way to find out the ISP assigned IP address?

I've looked into the Inet and WifiManager API's and all they seem to give you is your local network ip address. The code I tried below, just gives me my local address.

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
TextView ipaddr = (TextView)findViewById(R.id.address);
ipaddr.setText("Your IP Address is: " + ip);
Vadim Kotov
  • 7,103
  • 8
  • 44
  • 57
Crouch
  • 776
  • 2
  • 15
  • 31

2 Answers2

4

You make an HTTP call to a service that tells you what your external IP. An example of such a service is ipify.

https://api.ipify.org/

Documentation: https://www.ipify.org

Excerpt:

try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("https://api.ipify.org").openStream(), "UTF-8").useDelimiter("\\A")) {
    System.out.println("My current IP address is " + s.next());
} catch (java.io.IOException e) {
    e.printStackTrace();
}
Dev
  • 10,959
  • 3
  • 36
  • 50
  • Whilst this may theoretically answer the question, [it would be preferable](//meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference. – OneCricketeer Jan 13 '17 at 16:38
  • I tried it, dunno why it doesn't work for me, it skips that part of the code – FabioR Jul 16 '19 at 22:05
1

Try this:

    try {
        URL ip = new URL("http://checkip.amazonaws.com/");
        BufferedReader in = new BufferedReader(new InputStreamReader(ip.openStream()));

        System.out.println(in.readLine());
    } catch (IOException e) {
        e.printStackTrace();
    }
Planck Constant
  • 1,129
  • 14
  • 18
  • Of course. My code only shows how to get IP address. And it should be used correctly in Android – Planck Constant Jan 13 '17 at 14:01
  • Thanks @Uata it works fine, it took a bit of fiddling around with the ASyncTask to get it to work but you did right not to add that code in there. It stops me being lazy – Crouch Jan 16 '17 at 10:59