Thursday, 31 March 2016

How to track location using IP address in Java ?

Here I Use GeoLite Databse 



       
import java.io.File;
import java.io.IOException;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;


public class GetLocationExample {

  public static void main(String[] args) {
 GetLocationExample obj = new GetLocationExample();
 ServerLocation location = obj.getLocation(args[0]);
 System.out.println(location);
  }

  public ServerLocation getLocation(String ipAddress) {

 File file = new File(
     "GeoLiteCity.dat");
 return getLocation(ipAddress, file);

  }

  public ServerLocation getLocation(String ipAddress, File file) {

 ServerLocation serverLocation = null;

 try {

 serverLocation = new ServerLocation();

 LookupService lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE);
 Location locationServices = lookup.getLocation(ipAddress);

 serverLocation.setCountryCode(locationServices.countryCode);
 serverLocation.setCountryName(locationServices.countryName);
 serverLocation.setRegion(locationServices.region);
 serverLocation.setRegionName(regionName.regionNameByCode(
             locationServices.countryCode, locationServices.region));
 serverLocation.setCity(locationServices.city);
 serverLocation.setPostalCode(locationServices.postalCode);
 serverLocation.setLatitude(String.valueOf(locationServices.latitude));
 serverLocation.setLongitude(String.valueOf(locationServices.longitude));

 } catch (IOException e) {
  System.err.println(e.getMessage());
 }

 return serverLocation;

  }
}
 

       
public class ServerLocation {

 private String countryCode;
 private String countryName;
 private String region;
 private String regionName;
 private String city;
 private String postalCode;
 private String latitude;
 private String longitude;

 @Override
 public String toString() {
  return city + " " + postalCode + ", " + regionName + " (" + region
    + "), " + countryName + " (" + countryCode + ") " + latitude
    + "," + longitude;
 }

 public String getCity() {
  return city;
 }

 public void setCity(String city) {
  this.city = city;
 }

 

It will need a jar file "geoip-api-1.2.10.jar" download.... And GeoLite DataBase  download....here.

set classpath of jar file And compile the java file in Console.
Run it As....>java GetLocationExample 104.238.94.32 

It will give City Addr of IP requested..It will Show As

No comments:

Post a Comment