简体   繁体   中英

Get Geolocation by IP (Spigot 1.8 & 1.13.2)

i Want to find out the geolocation by only providing the ip adress. My Aim is to save city, country, postal code and other informations.

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

Any short possibilities, to find out by only using ip?

There are a lot of websites that provide free databases for IP geolocation.

Examples include:

At the plugin startup you could download one of these databases and then query it locally during runtime.

If you choose do download the .bin format you will have to initialize a local database and then import the data. Otherwise you could just use the csv file with a Java library like opencsv .

From the documentation of 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 to documentation: http://opencsv.sourceforge.net

I recommend using http://ip-api.com/docs/api:newline_separated

You can then chose what information you need and create your HTTP-link like:

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

The result in this example would be:

success
United States
US
VA
Virginia
Ashburn
20149
America/New_York

So you can create a method in Java to read HTTP and split it at \\n to get the lines:

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;
}

just make sure not to create to many querys in a short amount of time since ip-api.com will ban you for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM