Click here to Skip to main content
12,625,912 members (25,175 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.8K views
3 bookmarked
Posted

Get Detailed IP Address Information of any JAVA Client

, 25 May 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This example shows you how you get detailed information of any client IP address such as Country Code, Country Name, City and many more.

Introduction

This example shows you how you get detail information of any client IP address such as Country Code, Country Name, City and many more. Here I use a 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 {
        // Add a handler to handle unknown properties (in case the API adds new properties to the response)
        MAPPER.addHandler(new DeserializationProblemHandler() {

            @Override
            public boolean handleUnknownProperty(DeserializationContext context, 
            JsonParser jp, JsonDeserializer<?> deserializer, 
            Object beanOrClass, String propertyName) throws IOException {
                // Do not fail - just log
                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); // Using the API
        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; // Using the API
        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;

        /**
         * @return the ip
         */
        public String getIp() {
            return ip;
        }

        /**
         * @param ip the ip to set
         */
        public void setIp(String ip) {
            this.ip = ip;
        }

        /**
         * @return the country_code
         */
        public String getCountry_code() {
            return country_code;
        }

        /**
         * @param country_code the country_code to set
         */
        public void setCountry_code(String country_code) {
            this.country_code = country_code;
        }

        /**
         * @return the country_name
         */
        public String getCountry_name() {
            return country_name;
        }

        /**
         * @param country_name the country_name to set
         */
        public void setCountry_name(String country_name) {
            this.country_name = country_name;
        }

        /**
         * @return the region_code
         */
        public String getRegion_code() {
            return region_code;
        }

        /**
         * @param region_code the region_code to set
         */
        public void setRegion_code(String region_code) {
            this.region_code = region_code;
        }

        /**
         * @return the region_name
         */
        public String getRegion_name() {
            return region_name;
        }

        /**
         * @param region_name the region_name to set
         */
        public void setRegion_name(String region_name) {
            this.region_name = region_name;
        }

        /**
         * @return the city
         */
        public String getCity() {
            return city;
        }

        /**
         * @param city the city to set
         */
        public void setCity(String city) {
            this.city = city;
        }

        /**
         * @return the zipcode
         */
        public String getZipcode() {
            return zipcode;
        }

        /**
         * @param zipcode the zipcode to set
         */
        public void setZipcode(String zipcode) {
            this.zipcode = zipcode;
        }

        /**
         * @return the latitude
         */
        public Double getLatitude() {
            return latitude;
        }

        /**
         * @param latitude the latitude to set
         */
        public void setLatitude(Double latitude) {
            this.latitude = latitude;
        }

        /**
         * @return the longitude
         */
        public Double getLongitude() {
            return longitude;
        }

        /**
         * @param longitude the longitude to set
         */
        public void setLongitude(Double longitude) {
            this.longitude = longitude;
        }

        /**
         * @return the metro_code
         */
        public String getMetro_code() {
            return metro_code;
        }

        /**
         * @param metro_code the metro_code to set
         */
        public void setMetro_code(String metro_code) {
            this.metro_code = metro_code;
        }

        /**
         * @return the area_code
         */
        public String getArea_code() {
            return area_code;
        }

        /**
         * @param area_code the area_code to set
         */
        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");

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

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 have any doubts, please post your questions. If you really like this article, please share it.

Don’t forget to vote or comment about my writing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Debopam Pal
Software Developer National Informatics Centre (NIC)
India India
Hello! Myself Debopam Pal. I've completed my MCA degree from West Bengal University of Technology at 2013. I'm from India. I’ve started to work with MS Technologies in 2013 specially in C# 4.0, ASP.NET 4.0. I've also worked in PHP 5. Now I work in JAVA/J2EE, Struts2. Currently I'm involved in a e-Governance Project since Jan, 2014. In my leisure time I write Blog, Articles as I think that every developer should contribute something otherwise resource will be finished one day. Thank you for your time.

Visit: Linkedin Profile | Facebook Profile | Google+ Profile | CodeProject Profile

You may also be interested in...

Pro
Pro

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 25 May 2014
Article Copyright 2014 by Debopam Pal
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid