package com.huhy.demo.ip2region;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;
import java.io.File;
import java.lang.reflect.Method;/**
* @author : huhy on 2018/10/10.
* @Project_name:springboot_self_gitlab
* @LOCAL:com.huhy.demo.ip2region
* @description:获取外网ip位置的工具类*/
public classIPUtils {/**
* @author huhy
* @ClassName:IPUtils
* @date 2018/10/10 15:01
* @Description: 根据外网ip获取位置信息*/
public staticString getIPInfo(String ip){//加载ip2region.db
String dbPath = IPUtils.class.getResource("/ip2region/ip2region.db").getPath();
File file= newFile(dbPath);if ( file.exists() == false) {
System.out.println("Error: Invalid ip2region.db file");
}//查询算法
int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree//DbSearcher.BINARY_ALGORITHM//Binary//DbSearcher.MEMORY_ALGORITYM//Memory
try{
DbConfig config= newDbConfig();
DbSearcher searcher= newDbSearcher(config, dbPath);//define the method
Method method = null;switch( algorithm )
{caseDbSearcher.BTREE_ALGORITHM:
method= searcher.getClass().getMethod("btreeSearch", String.class);break;caseDbSearcher.BINARY_ALGORITHM:
method= searcher.getClass().getMethod("binarySearch", String.class);break;caseDbSearcher.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);returndataBlock.getRegion();
}catch(Exception e) {
e.printStackTrace();
}return null;
}
}