通过 IP 获取地理定位(Spigot 1.8 和 1.13.2)

Get Geolocation by IP (Spigot 1.8 & 1.13.2)

我只想通过提供 ip 地址来找出地理位置。 我的目标是保存城市、国家、邮政编码等信息。

CraftPlayer cp = (CraftPlayer)p;
String adress = cp.getAddress();

任何短的可能性,仅通过 ip 找出?

有很多网站提供免费的 IP 地理定位数据库。

示例包括:

在插件启动时,您可以下载这些数据库之一,然后在运行时在本地查询它。

如果选择下载 .bin 格式,则必须初始化本地数据库,然后导入数据。否则,您可以将 csv 文件与 Java 库一起使用,例如 opencsv.

来自 opencsv 的文档:

For reading, create a bean to harbor the information you want to read, annotate the bean fields with the opencsv annotations, then do this:

List<MyBean> beans = new CsvToBeanBuilder(FileReader("yourfile.csv"))
    .withType(Visitors.class).build().parse();

Link 到文档:http://opencsv.sourceforge.net

我推荐使用http://ip-api.com/docs/api:newline_separated

然后您可以选择您需要的信息并创建您的 HTTP-link 如:

http://ip-api.com/line/8.8.8.8?fields=49471

本例中的结果为:

success
United States
US
VA
Virginia
Ashburn
20149
America/New_York

因此您可以在 Java 中创建一个方法来读取 HTTP 并在 \n 处拆分它以获取行:

private void whatever(String ip) {
    String ipinfo = getHttp("http://ip-api.com/line/" + ip + "?fields=49471");
    if (ipinfo == null || !ipinfo.startsWith("success")) {
        // TODO: failed
        return;
    }
    String[] lines = ipinfo.split("\n");
    // TODO: now you can get the info
    String country = lines[1];
    /*
    ...
     */
}

private static String getHttp(String url) {
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
        String line;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line).append(System.lineSeparator());
        }
        br.close();
        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

请确保不要在短时间内创建太多查询,因为 ip-api.com 会禁止您这样做。