LoginSignup
1
2

More than 5 years have passed since last update.

MaxMindが提供しているGeoLite2をScalaから利用してみる

Last updated at Posted at 2014-08-27

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を使おう。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2