GeoLite2のライセンスはCC BY-SA 3.0。
Java向けのライブラリを使う。
https://github.com/maxmind/GeoIP2-java
Scala向けの薄いラッパーの https://github.com/Sanoma-CDA/maxmind-geoip2-scala というのも見つけたけど、これくらいならJava APIを叩いてもいいかなと思った。
import java.io.File
import java.net.InetAddress
import com.maxmind.geoip2.DatabaseReader.Builder
import com.maxmind.geoip2.exception.AddressNotFoundException
object GeoipSample {
def main(args: Array[String]): Unit ={
val database = new File("/tmp/GeoLite2-Country.mmdb")
// This creates the DatabaseReader object, which should be reused across lookups.
val reader = new Builder(database).build()
val ipAddresses = Seq("128.101.101.101", "192.168.100.1", "183.79.135.206", "212.58.244.18")
ipAddresses foreach { ip =>
try {
println(reader.country(InetAddress.getByName(ip)))
} catch {
case e: AddressNotFoundException => println(e)
}
}
}
}
AddressNotFoundException
をキャッチしないといけない。
実行結果は以下。
Country [getContinent()=North America, getCountry()=United States, getRegisteredCountry()=United States, getRepresentedCountry()=, getTraits()=Traits [ipAddress=128.101.101.101, anonymousProxy=false, satelliteProvider=false, ]]
com.maxmind.geoip2.exception.AddressNotFoundException: The address 192.168.100.1 is not in the database.
Country [getContinent()=Asia, getCountry()=Japan, getRegisteredCountry()=Japan, getRepresentedCountry()=, getTraits()=Traits [ipAddress=183.79.135.206, anonymousProxy=false, satelliteProvider=false, ]]
Country [getContinent()=Europe, getCountry()=United Kingdom, getRegisteredCountry()=United Kingdom, getRepresentedCountry()=, getTraits()=Traits [ipAddress=212.58.244.18, anonymousProxy=false, satelliteProvider=false, ]]
GeoLiteはLegacyになったので、GeoLite2を使おう。