vidha
vidha

Reputation: 1277

How to programmatically get a public IP address?

I didn't find the right solution. The below code gives me local IP address (if I connected to Wifi, it gives IP address like 192.168.0.x), but I want public IP address (same as if I search in google " what is my IP ")

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;
}

OR

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
    String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());

Can anyone help? Thanks!

Upvotes: 7

Views: 12518

Answers (5)

I found this simple solution:

public String getExternalIpAddress() throws Exception {
    URL whatismyip = new URL("http://checkip.amazonaws.com");
    BufferedReader in = null;
    try {
        in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));
        String ip = in.readLine();
        return ip;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Remember that this must be run on a separate thread.

Upvotes: 8

Zia
Zia

Reputation: 755

You can do this with a simple thread. you need to create a function in Activity.class file, and need to request a url that will give your public IP in text form: "https://api.ipify.org/. Click to open.

Add this function call in your onCreate() function.

    getPublicIP();

Add this function in your MainActivity.class.

    private void getPublicIP() {

        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();

    }

Upvotes: 2

Anoop M Maddasseri
Anoop M Maddasseri

Reputation: 10569

You may use the WS https://api.whatismyip.com/ip.php from whatismyip.com : This would output only your IP address in the simple text. (No input required, output is optional)

You must be a Gold Level Member to access the API

Updated Answer

You can make use of the web service from ipify.org

Read through the documentation here

Use https://api.ipify.org/?format=json WS to get device public IP address. This would output your IP address in JSON format.

You should use ipify because:

  • You can use it without limit (even if you're doing millions of requests per minute).
  • It's always online and available, and its infrastructure is powered by Heroku, which means that regardless of whether the server running the API dies, or if there's an enormous tornado which destroys half of the east coast, ipify will still be running!
  • It works flawlessly with both IPv4 and IPv6 addresses, so no matter what sort of technology you're using, there won't be issues.

....................

....................

Upvotes: 12

greenapps
greenapps

Reputation: 11224

Make a call to a server like https://whatismyipaddress.com or http://howtofindmyipaddress.com/.

If you have the page source then parse the ip address out.

There are other servers who only return your ip address. Not a whole html page as above two. But i forgot which one...

Upvotes: -2

CommonsWare
CommonsWare

Reputation: 1007584

Step #1: Create a Web service that returns the requester's IP address

Step #2: Call that Web service from your app.

A device does not know its public IP address (unless that device was seriously misconfigured).

Upvotes: 20

Related Questions