I want to know the location of the user that is on our web application. The information should contain user's Country
and City
. I am unable to find a good way to do so using Java
or Spring Boot
. I have tried using GeoLite2-City
but it gives me exception saying that The address 10.212.134.200 is not in the database.
I was also getting this exception on my localhost
with ip 127.0.0.1
. Following is the code I have used:
// String ipAddress = httpServletRequest.getRemoteAddr();
public String getGeoLocation(String ipAddress) {
String geoLocation = "";
try {
File database = ResourceUtils.getFile("classpath:GeoLite2-City/GeoLite2-City.mmdb");;
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
CityResponse response = dbReader.city(InetAddress.getByName(ipAddress));
String countryName = response.getCountry().getName();
String cityName = response.getCity().getName();
String postal = response.getPostal().getCode();
String state = response.getLeastSpecificSubdivision().getName();
geoLocation = "Country: " + countryName + "cityName: " + cityName + "postal: " + postal + "state: " + state;
System.out.println(geoLocation);
} catch(Exception ex) {
logger.error("Exception occured while trying to get GeoLocation of user: " + ex);
}
return geoLocation;
}
But I am always getting exception.
I only have downloaded and added Geolite2-city
file. I am also not confirmed if I need to add any other file. The dependency I have added is:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.0</version>
</dependency>