SoFunction
Updated on 2025-05-04

Java implements the sharing of home instances through IP computing

There may be scenarios where different clients request the same server interface in the product.

For example, in mini programs, apps or browsers, if you need to analyze the requested home location, the premise is that you need to obtain the country or city where the request is located first. This positioning usually requires active authorization, and users are generally unwilling to provide it, so they need to calculate the home location through the requested IP.

IP addresses are generally divided into two types, IPV4 and IPV6, and the corresponding calculation methods are also different. Referring to the national dimension, each country has a corresponding network segment range, calculate the corresponding values ​​of the minimum and maximum IP addresses in the network segment, and then compare the requested IP addresses to determine which country's network segment range belongs to.

import .Ipv4Util;
import ;
import ;
import ;

public class IpCalculate {
    public static void main(String[] args) throws Exception {
        // IPv4 network segment        String ipv4Network = "IPv4 network segment";
        String[] ipv4Param = (ipv4Network, "/");

        // IPv4 start and end IP        String ipv4StartIp = (ipv4Param[0],(ipv4Param[1]));
        String ipv4OverIp = (ipv4Param[0],(ipv4Param[1]));
        (ipv4StartIp);
        (ipv4OverIp);

        // IPv4 The corresponding long value of IP start and end        (Ipv4Util.ipv4ToLong(ipv4StartIp));
        (Ipv4Util.ipv4ToLong(ipv4OverIp));

        // IPv6 network segment        String ipv6Network = "IPv6 network segment";
        String[] ipv6Param =("/");
        int prefixLength = (ipv6Param[1]);

        // IPv6 start and end IP        InetAddress baseAddress = (ipv6Param[0]);
        BigInteger baseValue = new BigInteger(1, ());
        BigInteger mask = (128).subtract()
                .shiftRight(128 - prefixLength).shiftLeft(128 - prefixLength);
        BigInteger minIp = (mask);
        BigInteger maxIp = ((128 - prefixLength).subtract());
        (toIPv6String(minIp));
        (toIPv6String(maxIp));

        // IPv6 start and end IP long value        (minIp);
        (maxIp);
    }

    private static String toIPv6String(BigInteger value) throws Exception {
        byte[] bytes = ();
        byte[] ipv6Bytes = new byte[16];
        int start =  > 16 ?  - 16 : 0;
        int length = (, 16);
        (bytes, start, ipv6Bytes, 16 - length, length);
        return (ipv6Bytes).getHostAddress();
    }
}

However, the correspondence between network segment address and country needs to be maintained. If the home analysis does not need to be very accurate, you can directly use an open source dictionary library, such as the GeoIP2 component that is used more frequently.

<dependency>
  <groupId>.geoip2groupId>
  <artifactId>geoip2</artifactId>
</dependency>

Load the corresponding file dictionary through the API provided in the component, and then pass it in to the IP address for home judgment. Pay attention to the handling of disputes and sensitive areas here. If there is an error, the product will be more than a hot search problem.

import .;
import ;
import .Inet4Address;
import .Inet6Address;
import ;

public class GeoIpTool {
    public static void main(String[] args) throws Exception {

        // Read IP library files        File ipFile = new File("IP file library");
        DatabaseReader reader = new (ipFile).build();

        // IPV4 address        InetAddress ipV4 = ("IPV4");
        if (ipV4 instanceof Inet4Address){
            ((ipV4));
            ((ipV4).getCountry());
            // Default English name            ((ipV4).getCountry().getName());
            // Query the Chinese name            ((ipV4).getCountry().getNames().get("zh-CN"));
        }

        // IPV6 address        InetAddress ipV6 = ("IPV6");
        if (ipV6 instanceof Inet6Address){
            ((ipV6));
            ((ipV6).getCountry());
            // Default English name            ((ipV6).getCountry().getName());
            // Query the Chinese name            ((ipV6).getCountry().getNames().get("zh-CN"));
        }
    }
}

If you need very accurate real-time home analysis, you can purchase professional IP network segment data and update it in real time to the local database. Use it as an IP dictionary. After obtaining the requested IP, you can directly match the range.

CREATE TABLE `ip_place` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `network` varchar(100) DEFAULT NULL COMMENT 'Net segment interval',
  `min_ip` bigint(20) DEFAULT NULL COMMENT 'Minimum IP',
  `max_ip` bigint(20) DEFAULT NULL COMMENT 'Maximum IP',
  `min_ip_number` bigint(20) DEFAULT NULL COMMENT 'Minimum IP value',
  `max_ip_number` bigint(20) DEFAULT NULL COMMENT 'Maximum IP value',
  `ip_place` varchar(100) DEFAULT NULL COMMENT 'Addition',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='IP home';

Finally, it is necessary to add that for many standard data, try to design dictionary enumeration or data tables at the beginning of the project to avoid facing data cleaning problems during subsequent specifications.

This is the article about Java implementation of the analysis of the home instance through IP computing. For more information about the analysis of home content through IP computing, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!