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>
10.212.134.200 and 127.0.0.1 are addresses that have a meaning only inside your network, or inside your machine, not on the internet. There is no way for MaxMind to know where these are located. (You may be able to tell which city you are in by looking out of the window.)
If the request actually comes from the internet, so from outside your network, it is perhaps proxied. If that is the case, it is possible that the proxy has added a
X-Forwarded-For
orX-Real-IP
request header or similar containing the external ("real") IP address of the original requester. You would feed that intogetGeoLocation
.