How to retrieve location information based on an IP address in Java?

In Java, third-party libraries like GeoIP2 and ip2region can be used to retrieve the location based on an IP address.

  1. Utilize the GeoIP2 library:

Firstly, you need to download the GeoIP2 Java library and then use it in your code to retrieve the location of an IP address.

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. Utilize the ip2region library.

ip2region is a Java implementation of a pure IP database, which allows for fast retrieval of location information based on an IP address.

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

The above are two commonly used methods to choose the appropriate tool for obtaining the geographical location of an IP address based on specific needs.

广告
Closing in 10 seconds
bannerAds