Commit 3f5473cd authored by 杨林's avatar 杨林

从IP获取信息

parent 0e703196
package tools.geoip
import com.maxmind.geoip2.DatabaseReader
import com.maxmind.geoip2.model.{AsnResponse, CityResponse}
import com.maxmind.geoip2.record.{City, Country, Subdivision}
import model.IpItem
import java.io.File
import java.net.InetAddress
import scala.io.Source
import scala.language.postfixOps
/**
* Created with IntelliJ IDEA.
* Class: GeoIp
* Description: 解析ip类
* User: lin
* Date: 2021-07-19
* Time: 18:31
*/
class GeoIp(ip: String) {
private[this] val database: File = new File("src/main/resources/GeoLite2-City.mmdb")
private[this] val asnDatabase = new File("src/main/resources/GeoLite2-ASN.mmdb")
private[this] val reader: DatabaseReader = new DatabaseReader.Builder(database).build
private[this] val asnReader = new DatabaseReader.Builder(asnDatabase).build
private[this] val address: InetAddress = InetAddress.getByName(ip)
private[this] val response: CityResponse = reader.city(address)
private[this] val asnResponse: AsnResponse = asnReader.asn(address)
private[this] val country: Country = response.getCountry
private[this] val subdivision: Subdivision = response.getMostSpecificSubdivision
private[this] val city: City = response.getCity
/**
* 根据给定ip
*
* @return 根据ip得到信息
*/
def getCity: IpItem =
IpItem(
ip = ip,
countryName = country.getNames.get("zh-CN"),
countryNameEN = country.getName, isoCode = country.getIsoCode,
subName = subdivision.getNames.get("zh-CN"),
subNameEN = subdivision.getName,
subCode = subdivision.getIsoCode,
cityName = city.getNames.get("zh-CN"),
cityNameEN = city.getName,
organization = asnResponse.getAutonomousSystemOrganization
)
}
object GeoIp extends App {
def apply(ip: String): GeoIp = new GeoIp(ip)
println(apply("39.149.36.225").getCity)
val source = Source.fromFile(new File("src/main/resources/ip.txt"))
source.getLines().map(x => apply(x).getCity).foreach(println)
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment