根据ip获取对应国家城市信息,全球ip,部分国外获取不到城市

活不多说直接上代码,需要引入ip2region.jar,可以直接去maven库找。

 

package com.doitlite.cms.util;

import java.io.File;
import java.lang.reflect.Method;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

public class AddressUtils {

	  public static String getCityInfo(String ip) {
		  
	        //db
	        String dbPath = AddressUtils.class.getResource("/data/ip2region.db").getPath();
	 
	        File file = new File(dbPath);
	        if (file.exists() == false) {
	            System.out.println("Error: Invalid ip2region.db file");
	        }
	 
	        //查询算法
	        int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
	        //int algorithm = DbSearcher.BINARY_ALGORITHM; //Binary
	        //int algorithm = DbSearcher.MEMORY_ALGORITYM; //Memory
	        try {
	            DbConfig config = new DbConfig();
	            DbSearcher searcher = new DbSearcher(config, dbPath);
	 
	            //define the method
	            Method method = null;
	            switch (algorithm) {
	                case DbSearcher.BTREE_ALGORITHM:
	                    method = searcher.getClass().getMethod("btreeSearch", String.class);
	                    break;
	                case DbSearcher.BINARY_ALGORITHM:
	                    method = searcher.getClass().getMethod("binarySearch", String.class);
	                    break;
	                case DbSearcher.MEMORY_ALGORITYM:
	                    method = searcher.getClass().getMethod("memorySearch", String.class);
	                    break;
	            }
	 
	            DataBlock dataBlock = null;
	            if (Util.isIpAddress(ip) == false) {
	                System.out.println("Error: Invalid ip address");
	            }
	 
	            dataBlock = (DataBlock) method.invoke(searcher, ip);
	 
	            return dataBlock.getRegion();
	 
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	 
	        return null;
	    }
	 
	    public static void main(String[] args) throws Exception {
	        String ip="12.24.100.20";
	        String cityIpString = getCityInfo(ip);
	        System.out.println(cityIpString); //中国|0|广东省|深圳市|电信
	        String[] splitIpString = cityIpString.split("\\|");
	        cityIpString =splitIpString[3].replaceAll("市","");
	        System.err.println(cityIpString);
	    }


}

效果:

根据ip获取对应国家城市信息,全球ip,部分国外获取不到城市_第1张图片

 

注意需要使用到一些资源文件:https://download.csdn.net/download/w491797259/12434715

目录结构如下:

根据ip获取对应国家城市信息,全球ip,部分国外获取不到城市_第2张图片

你可能感兴趣的:(根据ip获取对应国家城市信息,全球ip,部分国外获取不到城市)