赞
踩
- <!-- https://mvnrepository.com/artifact/org.lionsoul/ip2region -->
- <dependency>
- <groupId>org.lionsoul</groupId>
- <artifactId>ip2region</artifactId>
- <version>2.7.0</version>
- </dependency>
地址:https://gitcode.com/lionsoul2014/ip2region/overview
将数据文件下载下来放到resources:
-
- public class IPUtil {
-
- /**
- * 将整个xdb文件加载到内存中
- */
- private final static Searcher SEARCHER;
-
- static {
- try {
- ClassPathResource resource = new ClassPathResource("ip2region.xdb");
- String path = resource.getURL().getPath();
- byte[] cBuff = Searcher.loadContentFromFile(path);
- SEARCHER = Searcher.newWithBuffer(cBuff);
- } catch (Exception e) {
- throw new RuntimeException("初始化ip2region.xdb异常!");
- }
- }
-
- /**
- * @Description 获取ip地址信息
- * @param ipStr 192.168.0.1
- * @Throws
- * @Return java.util.List<java.lang.String> 返回结果形式(国家|区域|省份|城市|ISP)
- * @Date 2024-03-08 17:43:45
- * @Author WangKun
- */
- public static List<String> getIpAddress(String ipStr) {
- return getIpAddress(ipStr, null);
- }
-
-
- /**
- * @Description 获取ip地址信息
- * @param ipStr ip 经过转换后的
- * @param index
- * @Throws
- * @Return java.util.List<java.lang.String>
- * @Date 2024-03-08 17:43:51
- * @Author WangKun
- */
- public static List<String> getIpAddress(String ipStr, int[] index) {
- try {
- long ip = Searcher.checkIP(ipStr);
- return getIpAddress(ip, index);
- } catch (Exception e) {
- throw new RuntimeException("ip解析为long系统异常!");
- }
- }
-
- /**
- * @Description 获取ip地址信息
- * @param ip
- * @param index
- * @Throws
- * @Return java.util.List<java.lang.String>
- * @Date 2024-03-08 17:43:55
- * @Author WangKun
- */
- public static List<String> getIpAddress(Long ip, int[] index) {
- //获取xdb文件资源
- List<String> regionList = new ArrayList<>();
- try {
- String region = SEARCHER.search(ip);
- String[] split = region.split("\\|");
- if (index == null) {
- regionList = Arrays.asList(split);
- } else {
- for (int i : index) {
- regionList.add(split[i]);
- }
- }
- //关闭资源
- SEARCHER.close();
- } catch (Exception e) {
- throw new RuntimeException("ip解析地址异常!");
- }
- return regionList;
- }
-
-
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。