2

Possible Duplicate:
How to get ip address of the device?

Below is a snippet of how I am trying to get the external IP. However, it does not return anything...

public String getIpAddress() {

    try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet("http://www.whatismyip.com/?404");
            // HttpGet httpget = new HttpGet("http://whatismyip.com.au/");
            // HttpGet httpget = new HttpGet("http://www.whatismyip.org/");
            HttpResponse response;

            response = httpclient.execute(httpget);

            //Log.i("externalip",response.getStatusLine().toString());

            HttpEntity entity = response.getEntity();
            entity.getContentLength();
            str = EntityUtils.toString(entity);
    }
    catch (Exception e)
    {
    }
    return str;

}
Community
  • 1
  • 1
omi0301
  • 473
  • 2
  • 5
  • 15

2 Answers2

12
public String getIpAddress() {
String ip;
   try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
        // HttpGet httpget = new HttpGet("http://whatismyip.com.au/");
        // HttpGet httpget = new HttpGet("http://www.whatismyip.org/");
        HttpResponse response;

        response = httpclient.execute(httpget);
        //Log.i("externalip",response.getStatusLine().toString());

        HttpEntity entity = response.getEntity();
        entity.getContentLength();
        str = EntityUtils.toString(entity);
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
        JSONObject json_data = new JSONObject(str);
        ip = json_data.getString("ip");
        Toast.makeText(getApplicationContext(), ip, Toast.LENGTH_LONG).show();
    }
    catch (Exception e){...}

  return ip;
}

OR

UPDATE FEB 2015

WhatIsMyIp now exposes a developer API that you can use.

Nirav Ranpara
  • 13,753
  • 3
  • 39
  • 54
0

you can have a look here http://code.google.com/p/external-ip/source/browse/src/org/kost/externalip/ExternalIP.java

and also here External ip address in android programatically

Community
  • 1
  • 1
Adrian Herea
  • 658
  • 6
  • 7