Introduction
This example shows how you can get detailed information of any client IP address such as Country Code, Country Name, City and many more. Here, I use an API provided by freegeoip. freegeoip is a public REST API for searching geolocation of IP addresses and host names. It has an internal database with geolocation information, which is queried via the API. There’s no sorcery, it’s just a database.
Background
This example is dependent on the following libraries:
Quick Start
Creating the Class IP
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
public class IP {
private static final HttpClient HTTP_CLIENT = new DefaultHttpClient();
private static final ObjectMapper MAPPER = new ObjectMapper();
static {
MAPPER.addHandler(new DeserializationProblemHandler() {
@Override
public boolean handleUnknownProperty(DeserializationContext context,
JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass,
String propertyName) throws IOException {
String className = (beanOrClass instanceof Class) ?
((Class) beanOrClass).getName() : beanOrClass.getClass().getName();
System.out.println("Unknown property while de-serializing: " +
className + "." + propertyName);
context.getParser().skipChildren();
return true;
}
});
}
public static IPInfo getIPInfo(HttpServletRequest request) {
String url = "http://freegeoip.net/json/" + getClientIP(request);
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = HTTP_CLIENT.execute(httpGet, new BasicHttpContext());
String responseString;
IPInfo ipResponse;
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("Sorry! Response Error. Status Code: " +
httpResponse.getStatusLine().getStatusCode());
}
responseString = EntityUtils.toString(httpResponse.getEntity());
ipResponse = MAPPER.readValue(responseString, IPInfo.class);
return ipResponse;
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public static IPInfo getIPInfo(String ip) {
String url = "http://freegeoip.net/" + ip;
try {
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = HTTP_CLIENT.execute(httpGet, new BasicHttpContext());
String responseString;
IPInfo ipInfo;
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
throw new RuntimeException("Sorry! Response Error. Status Code: " +
httpResponse.getStatusLine().getStatusCode());
}
responseString = EntityUtils.toString(httpResponse.getEntity());
ipInfo = MAPPER.readValue(responseString, IPInfo.class);
return ipInfo;
} catch (Exception ex) {
System.out.println(ex.toString());
} finally {
HTTP_CLIENT.getConnectionManager().shutdown();
}
}
public static String getClientIP(HttpServletRequest request) {
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
return ipAddress;
}
public static class IPInfo {
private String ip;
private String country_code;
private String country_name;
private String region_code;
private String region_name;
private String city;
private String zipcode;
private Double latitude;
private Double longitude;
private String metro_code;
private String area_code;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getCountry_code() {
return country_code;
}
public void setCountry_code(String country_code) {
this.country_code = country_code;
}
public String getCountry_name() {
return country_name;
}
public void setCountry_name(String country_name) {
this.country_name = country_name;
}
public String getRegion_code() {
return region_code;
}
public void setRegion_code(String region_code) {
this.region_code = region_code;
}
public String getRegion_name() {
return region_name;
}
public void setRegion_name(String region_name) {
this.region_name = region_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public Double getLatitude() {
return latitude;
}
public void setLatitude(Double latitude) {
this.latitude = latitude;
}
public Double getLongitude() {
return longitude;
}
public void setLongitude(Double longitude) {
this.longitude = longitude;
}
public String getMetro_code() {
return metro_code;
}
public void setMetro_code(String metro_code) {
this.metro_code = metro_code;
}
public String getArea_code() {
return area_code;
}
public void setArea_code(String area_code) {
this.area_code = area_code;
}
@Override
public String toString() {
return "IPInfo{"
+ "\"ip\":\"" + ip + "\""
+ ",\"country_code\":\"" + country_code + "\""
+ ",\"country_name\":\"" + country_name + "\""
+ ",\"region_code\":\"" + region_code + "\""
+ ",\"region_name\":\"" + region_name + "\""
+ ",\"city\":\"" + city + "\""
+ ",\"zipcode\":\"" + zipcode + "\""
+ ",\"latitude\":" + latitude
+ ",\"longitude\":" + longitude
+ ",\"metro_code\":\"" + metro_code + "\""
+ ",\"area_code\":\"" + area_code + "\""
+ '}';
}
}
}
How to Call
IP.IPInfo ipInfo = IP.getIPInfo("117.227.59.29");<br />
ipInfo.getCountry_name()
shows you the Country Name, e.g. India.
As you can see, here I use JSON Parser as the response string of the API which is in JSON Format. You can get the response in CSV or XML Format also. See the API usage below.
API Usage
Send HTTP GET requests to:
http://freegeoip.net/{format}/{ip_or_hostname
}
The API Supports
Both HTTP and HTTPS.
Supported Formats are
CSV, XML or JSON, which also support the callback query argument for JSONP.
Note
The ip_or_hostname
part is optional. Your own IP is searched if one is not provided.
Limitation
API usage is limited to 10,000 queries per hour. After reaching this limit, all requests will result in HTTP 403 (Forbidden) until the roll over.
Reference
If you've any doubt, please post your questions. If you really like this article, please share it.
Don’t forget to vote or comment about my writing.
CodeProject