Java - найти местоположение по IP-адресу

Java - найти местоположение, используя IP-адрес

Geolocation

В этом примере мы покажем вам, как найти местоположение (страна, город, широта, долгота), используя IP-адрес.

1. База данных GeoLite

MaxMind предоставляет бесплатную базу данных GeoLite (IP-адрес для местоположения).

  1. Получите бесплатные бесплатные базы данных GeoLite -here

  2. Получите API Java для клиента GeoIP -here

  3. Начните код это.

2. Пример Java GeoLite

Пример использования Java-API GeoIP-клиента для поиска местоположения по IP-адресу.

GetLocationExample.java

package com.example.analysis.location;

import java.io.File;
import java.io.IOException;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import com.example.analysis.location.mode.ServerLocation;

public class GetLocationExample {

  public static void main(String[] args) {
    GetLocationExample obj = new GetLocationExample();
    ServerLocation location = obj.getLocation("206.190.36.45");
    System.out.println(location);
  }

  public ServerLocation getLocation(String ipAddress) {

    File file = new File(
        "C:\\resources\\location\\GeoLiteCity.dat");
    return getLocation(ipAddress, file);

  }

  public ServerLocation getLocation(String ipAddress, File file) {

    ServerLocation serverLocation = null;

    try {

    serverLocation = new ServerLocation();

    LookupService lookup = new LookupService(file,LookupService.GEOIP_MEMORY_CACHE);
    Location locationServices = lookup.getLocation(ipAddress);

    serverLocation.setCountryCode(locationServices.countryCode);
    serverLocation.setCountryName(locationServices.countryName);
    serverLocation.setRegion(locationServices.region);
    serverLocation.setRegionName(regionName.regionNameByCode(
             locationServices.countryCode, locationServices.region));
    serverLocation.setCity(locationServices.city);
    serverLocation.setPostalCode(locationServices.postalCode);
    serverLocation.setLatitude(String.valueOf(locationServices.latitude));
    serverLocation.setLongitude(String.valueOf(locationServices.longitude));

    } catch (IOException e) {
        System.err.println(e.getMessage());
    }

    return serverLocation;

  }
}

Выход

ServerLocation [countryCode=US, countryName=United States, region=CA,
    regionName=California, city=Sunnyvale, postalCode=94089,
    latitude=37.424896, longitude=-122.0074]