介绍
github
https://github.com/snowfigure/ip2region
> 数据 https://github.com/snowfigure/ip2region/tree/master/data/ip2region.db
gitee
https://gitee.com/lionsoul/ip2region
> 数据 https://gitee.com/lionsoul/ip2region/tree/master/data/ip2region.db
ip2region - 最自由的 ip 地址查询库,ip 到地区的映射库,提供 Binary,B 树和纯内存三种查询算法,妈妈再也不用担心我的 ip 地址定位。
Maven 仓库
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>1.7.2</version>
</dependency>
操作
把
ip2region.db
复制到 maven 项目的resources
目录下(当前项目为 properties 目录).
工具类代码
package ink.fdq.snowy.core.kits;
import java.lang.reflect.Method;
import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IpKit {
public static boolean isIPAddress(String ipaddr) {
boolean flag = false;
Pattern pattern = Pattern.compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");
Matcher m = pattern.matcher(ipaddr);
flag = m.matches();
return flag;
}
/**
* 获取IP地址所在地
* 国内地址 类似:中国|0|四川省|成都市|电信 中国|0|上海|上海市|联通 中国|0|北京|北京市|阿里云
* 国外地址 类似:日本|0|东京都|东京|0 美国|0|加利福尼亚|0|0
* @param ip
* @return
*/
public static String getCityInfo(String ip){
//db
String dbPath = IpKit.class.getResource("/ip/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
//DbSearcher.BINARY_ALGORITHM //Binary
//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 ( isIPAddress(ip) == false ) {
System.out.println("Error: Invalid ip address");
return null;
}
dataBlock = (DataBlock) method.invoke(searcher, ip);
return dataBlock.getRegion();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception{
System.err.println(getCityInfo("47.95.208.126"));
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于