How to get visitors IP address in Java?


This is tough task i searched around the Google , Tones of codes but after so many test i got the solution for this. This is very simple let me explain how you can get IP address of visitor. There is questions of programmers like "how to get client's IP Address in Java?"








  • I know you tried "request.getRemoteAddr()" but its not working and give you 127.0.0.1 as an output.
Sample code to get IP address

request.getHeader("VIA");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
       if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
       }

This code works perfectly i tested it on my server. Now you have IP address but after that question is how to get Country, City, Latitude, Longitude using Java? This will be done by javaQuery API. For that u can try below code.

Important notice for existing user (javaQueryAPI 7.0 or less) : Please check the new changes in javaQueryAPI 8.0 before installing API in your project.

/*
* javaQueryAPI 7.0 or less
*/
import javaQuery.j2ee.GeoLocation
request.getHeader("VIA");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
       if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
       }
GeoLocation gl = new GeoLocation();
gl.GetGeoLocationByIP(ipAddress);
String country = gl.Country;
/*
* javaQueryAPI 8.0 or above
*/
import javaQuery.importClass.javaQueryBundle;
import javaQuery.j2ee.GeoLocation;

request.getHeader("VIA");
String ipAddress = request.getHeader("X-FORWARDED-FOR");
       if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
       }
        GeoLocation $gl = javaQueryBundle.createGeoLocation();
        $gl.MAPTargetByIP("117.204.232.104", "This is Demo. You can set even NULL");
        System.out.println($gl.Latitude);
        System.out.println($gl.Longitude);
        System.out.println($gl.Country);
        System.out.println($gl.City);
        System.out.println($gl.State);
        System.out.println($gl.GoogleMap_URL);
        System.out.println($gl.GoogleMap_URL_Bubble);
   
/*
* output
* 23.0333
* 72.616699
* India
* Ahmedabad
* Gujarat
* http://maps.google.com/maps?q=23.0333,+72.616699+(117.204.232.104)&iwloc=A&hl=en
* http://maps.google.com/maps?q=23.0333,+72.616699+(This is Demo. You can set even NULL)&iwloc=A&hl=en
*/

Some of users facing that its not working. It won't work on local machine as it won't resolve the data for 127.0.0.1 . Upload your file on server and access page through any browser.

Check out the http://www.javaquery.com/p/javaquery-api.html for download.

0 comments :

Note: only a member of this blog may post a comment.