This question already has an answer here:
- Determine device public ip 13 answers
I am developing an application in android 2.1 and I want to display the external IP. How could I do this? Thanks in advance.
This question already has an answer here:
I am developing an application in android 2.1 and I want to display the external IP. How could I do this? Thanks in advance.
public void getCurrentIP () {
ip.setText("Please wait...");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://ifcfg.me/ip");
// HttpGet httpget = new HttpGet("http://ipecho.net/plain");
HttpResponse response;
response = httpclient.execute(httpget);
//Log.i("externalip",response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len != -1 && len < 1024) {
String str=EntityUtils.toString(entity);
//Log.i("externalip",str);
ip.setText(str);
} else {
ip.setText("Response too long or error.");
//debug
//ip.setText("Response too long or error: "+EntityUtils.toString(entity));
//Log.i("externalip",EntityUtils.toString(entity));
}
} else {
ip.setText("Null:"+response.getStatusLine().toString());
}
}
catch (Exception e)
{
ip.setText("Error");
}
}
http://api.externalip.net/ip will return your ip in simple api format
You can read more about getting the external ip here: http://www.externalip.net/api
I don't think that there is a way to do it programmatically but you could call up a site like http://www.whatismyip.com/ and then strip out the IP from the page. You might want to find a site that offers an API and supports 3rd party calls.
Take a look at this code snippet:
String ipAddress = null;
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()) {
ipAddress = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
Log.e("IP ADDRESS:", ipAddress);