IP地址查询城市

偶然学习到,根据ip地址区查询城市地址,首先得先获取一些ip对应的城市。

我是根据ip2region 数据库中进行查询的,将获取的IP地址与数据库中的数据进行匹配,可以确定该 IP 地址所属的地理位置信息。

maven需要导入依赖ip2region库,ip2region.db再资源中下载。

        <!--ip库-->
        <dependency>
        <groupId>org.lionsoul</groupId>
        <artifactId>ip2region</artifactId>
        <version>1.7.2</version>
        </dependency>
public static String getIpAddress(String ip, int algorithm) {
        // ip2region.db数据存放的路径
        String path=FileUtil.getIp2regin()+"ip2region.db";
        if (Util.isIpAddress(ip)) {
            // 查询算法B-tree, Binary, Memory
            DbSearcher searcher = null;
            try {
                DbConfig config = new DbConfig();
                searcher = new DbSearcher(config, path);
                Method method;
                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:
                    default:
                        method = searcher.getClass().getMethod("memorySearch", String.class);
                        break;
                }
                DataBlock dataBlock = (DataBlock) method.invoke(searcher, ip);
                List<String> list = Arrays.asList(dataBlock.getRegion().split("\\|")).stream().filter(s -> !"0".equals(s)).collect(Collectors.toList());
                String ipAddress = StringUtils.join(list, ",");
                String[] split = ipAddress.split(",");
                return split[split.length-2];
            } catch (Exception e) {
                System.err.println("获取城市信息失败:"+e);
            } finally {
                try {
                    searcher.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else if ("127.0.0.1".equals(ip) || StringUtils.startsWith(ip, "192.168")) {
            return "内网IP";
        }
        return DEFAULT_CITY_NAME;
    }

 仅供学习参考,所以数据不是最新的。ip2region 数据库可能存在一定的更新滞后性。新添加的 IP 地址或地理位置信息可能需要一定的时间才会被纳入到数据库中。因此,在某些情况下,可能会出现无法查询到特定 IP 地址对应城市的情况。此外,还有一些其他因素可能导致查询不到 IP 地址对应的城市信息,例如输入的 IP 地址错误、数据库文件缺失或损坏等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值