Java – IPアドレスを使用して位置を見つける

この例では、IPアドレスを使用して場所(国、都市、緯度、経度)を見つける方法を示します。
1. GeoLiteデータベース
MaxMind
は無料のGeoLiteデータベース(IPアドレスからロケーション)を提供します。
-
無料のGeoLiteを無料で入手するデータベース –
here
。 GeoIPクライアントJava APIを入手する –
here
。コードを開始します。
2. GeoLite Javaの例
GeoIPクライアントJava APIを使用してIPアドレスを使用して場所を見つける例。
GetLocationExample.java
package com.mkyong.analysis.location;
import java.io.File;
import java.io.IOException;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import com.mkyong.analysis.location.mode.ServerLocation;
public class GetLocationExample {
public static void main(String[]args) {
GetLocationExample obj = new GetLocationExample();
ServerLocation location = obj.getLocation("206.190.36.45");
System.out.println(location);
}
public ServerLocation getLocation(String ipAddress) {
File file = new File(
"C:\\resources\\location\\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;
}
}
出力
ServerLocation[countryCode=US, countryName=United States, region=CA,
regionName=California, city=Sunnyvale, postalCode=94089,
latitude=37.424896, longitude=-122.0074]....
=== 参考文献
. http://en.wikipedia.org/wiki/Geolocation__software[Wikipedia:
ジオロケーションソフトウェア]。 http://dev.maxmind.com/geoip/legacy/geolite/[GeoLite無料ダウンロード可能
データベース]
link://tag/geoip/[geoip]link://タグ/java/[java]