An easy way is with GeoLite (http://dev.maxmind.com/geoip/legacy/geolite/). Because it uses a local database no web service calls are needed and it's much faster for geocoding large numbers of IPs.
Here is how:
Add this Maven artifact:
<dependency>
<groupId>com.maxmind.geoip</groupId>
<artifactId>geoip-api</artifactId>
<version>1.2.11</version>
</dependency>
Download the geolocation data file from http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
Unpack the file into any folder. Then do:
LookupService cl = new LookupService("/var/geolite/GeoLiteCity.dat",
LookupService.GEOIP_MEMORY_CACHE | LookupService.GEOIP_CHECK_CACHE);
Location location = cl.getLocation("some ip address");
The result will be in the Location object in the latitude, longitude, city, region and countryCode properties.
Please take a look at their accuracy estimates to ensure it meets the needs of your project: http://www.maxmind.com/en/geolite_city_accuracy .
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…