共計 1171 個字符,預計需要花費 3 分鐘才能閱讀完成。
Java 中可以使用第三方庫來根據 IP 地址獲取歸屬地,其中比較常用的庫是 GeoIP2 和 ip2region。
- 使用 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);
}
}
- 使用 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 地址的歸屬地。
丸趣 TV 網 – 提供最優質的資源集合!
正文完