溫馨提示×

Java怎么根據ip地址獲取歸屬地

小億
445
2024-03-08 15:41:28
欄目: 編程語言

Java中可以使用第三方庫來根據IP地址獲取歸屬地,其中比較常用的庫是GeoIP2和ip2region。

  1. 使用GeoIP2庫:

首先需要下載GeoIP2的Java庫,然后在代碼中使用該庫來獲取IP地址的歸屬地。

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import java.io.File;
import java.net.InetAddress;

public class IPUtil {

    public static void main(String[] args) throws Exception {
        File database = new File("/path/to/GeoLite2-City.mmdb");
        DatabaseReader reader = new DatabaseReader.Builder(database).build();

        InetAddress ipAddress = InetAddress.getByName("128.101.101.101");
        CityResponse response = reader.city(ipAddress);

        String country = response.getCountry().getName();
        String city = response.getCity().getName();

        System.out.println("Country: " + country);
        System.out.println("City: " + city);
    }
}
  1. 使用ip2region庫:

ip2region是一個純真IP數據庫的java實現,可以根據IP地址快速查找歸屬地。

import org.lionsoul.ip2region.*;
import java.io.IOException;

public class IPUtil {

    public static void main(String[] args) throws DbMakerConfigException, IOException {
        DbConfig config = new DbConfig();
        DbSearcher searcher = new DbSearcher(config, "/path/to/ip2region.db");

        DataBlock dataBlock = searcher.btreeSearch("128.101.101.101");

        String region = dataBlock.getRegion();

        System.out.println("Region: " + region);
    }
}

以上是兩種常用的方法,可以根據實際需求選擇合適的庫來獲取IP地址的歸屬地。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女