Finding Location from IP Address on Android

In this post, I am going to discuss finding location from IP address on Android device by programmatically. Sometime you might think why we need to find the IP address so will talk about why we need to find the IP address of the device in run time.

By IP address we are able to detect the location of the device. Sometime you may think we can get it using GPS yah that’s right but if the device doesn’t have GPS then what we do? Most of the third class low level devices don’t have GPS in this sort of situation we can use IP to find the location. Other thing if you use GPS then needs to consider about battery power too.

I can tell one example, recently we developed a music application, in that app we need to send current actual device login country information we want to save on our database so first we used GPS to find country other thing this is the only one place we need to find the country. If we put GPS access permission on manifest file, Google Play Store filter will reduces the number of compatibility devices amount so app reach amount also will reduce. In this app we only need country so we used IP address to find the country.

I know, somebody may suggest to use TelephonyManager (Telephony  service) or Localization settings.

TelephonyManager (Telephony  service)

Actually we use the getSimCountryIso() method of TelephoneManager

public static String getUserCountry(Context context) {

try {

final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

final String simCountry = tm.getSimCountryIso();

if (simCountry != null && simCountry.length() == 2) { // SIM country code is available

return simCountry.toLowerCase(Locale.US);

}

else if (tm.getPhoneType() != TelephonyManager.PHONE_TYPE_CDMA) { // device is not 3G (would be unreliable)

String networkCountry = tm.getNetworkCountryIso();

if (networkCountry != null && networkCountry.length() == 2) { // network country code is available

return networkCountry.toLowerCase(Locale.US);

}

}

}

catch (Exception e) { }

return null;

}

Since this is the SIM country code it also should not change when we are traveling to other countries. So using this one we cannot get current country device location.

Localization settings

String localCountry  = context.getResources().getConfiguration().locale.getCountry();

You can also replace getCountry() with getISO3Country() to get a 3 letter ISO code for the country.

This will get the country name:

 String diplayLocalCountry = context.getResources().getConfiguration().locale.getDisplayCountry();

This won’t work in countries for which Android does not have a Locale. For example, in Switzerland, the language is likely to be set to German or French. This method will give you Germany or France, not Switzerland.

So Telephony Manager and Localization settings are not effective way to find current country information.  So I am going to discuss how we can find device’s location very easily.

Everybody knows, We can easily find the internal IP address  but bit difficult to find the external IP of the device so I am going to tell you how to find the external IP programmatically.

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

}

The above code will return the local IP if you are in wifi but using this IP you are not able to find the country or anything so we need to find the external IP/public IP

If you want to find local country of the phone then use below code.

String locale = getApplicationContext().getResources().getConfiguration().locale.getDisplayCountry();

There are some free web services to get the external IP. You just only need to call it. For my example I am going to use http://ifconfig.me/ip.json web site.

 

public String getIpAddress() {

String ip = null;

try {

HttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet(“http://ifconfig.me/ip.json”);

HttpResponse response;

 

response = httpclient.execute(httpget);

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

 

HttpEntity entity = response.getEntity();

entity.getContentLength();

String str = EntityUtils.toString(entity);

ip = str;

}

catch (Exception e){

Log.e(“Error”, e.getMessage());

}

 

return ip;

}

Once you find the external IP address you may know the country by calling some other free web service. To get country info I am using http://freegeoip.net/json web site.

 

public String getCountry() {

String country = null;

try {

HttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet(“http://freegeoip.net/json”);

HttpResponse response;

 

response = httpclient.execute(httpget);

HttpEntity entity = response.getEntity();

entity.getContentLength();

String str = EntityUtils.toString(entity);

Log.i(“RESS”, str);

country = str;

}

catch (Exception e){

Log.e(“Error”, e.getMessage());

}

return country;

}

If you have any doubts feel free to contact me or put a comment below. I will ready to support you guys.

 

2 Comments

  1. German April 18, 2017
  2. Akram September 7, 2017

Add Comment