随笔 - 836  文章 - 1 评论 - 40 阅读 - 102万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

 

 

采用ip2region 来解析IP地址

1.下载离线的IP库
地址:https://github.com/lionsoul2014/ip2region/tree/master/data
下载ip2region.db

2.导入Maven依赖

<dependency>
    <groupId>org.lionsoul</groupId>
    <artifactId>ip2region</artifactId>
    <version>1.7.2</version>
</dependency>

3.编写解析IP工具类

默认的格式解析出来的是以’|’ 分割的,这里进行处理改成使用tab键进行分割

复制代码
public class IpUtils {

    /**
     * 解析Ip地址工具类,传入IP地址,返回省、市、城市、运行商,以\t分割
     */
    public static String parseIP(String ip) {
        String result = "";
        // 关联下载的id2region.db 离线库
        String dbFile = "E:\\stud\\IpParse\\ip2region\\data\\ip2region.db";
        try {
            DbSearcher search = new DbSearcher(new DbConfig(), dbFile);
            // 传入ip进行解析
            DataBlock dataBlock = search.btreeSearch(ip);
            // 获取解析后的数据  格式:国家|大区|省|市|运营商
            String region = dataBlock.getRegion();
            String replace = region.replace("|", ",");
            String[] splits = replace.split(",");
            if (splits.length == 5) {
                String country = splits[0];
                String province = splits[2];
                String city = splits[3];
                String operator = splits[4];
                // 拼接数据
                result = country + "\t" + province + "\t" + city + "\t" + operator;
            }
            return result;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
复制代码

4.工具类的调用

返回值detail即为我们解析后以\t拼接的信息

String detail = IpUtils.parseIP(ip);

 


 



posted on   lshan  阅读(541)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2021-06-30 redash 连接 drill
2021-06-30 Drill 连接mongo 查询错误
点击右上角即可分享
微信分享提示