JAVA根据ip地址获取归属地

IP获取归属地

1.通过地址库获取

        如果使用API接口获取,可能会出现服务挂了,或者服务地址不提供服务了等问题。而采用本地地址库就没有这些问题。

本文采用离线IP地址定位库 Ip2regionIp2region是一个离线IP地址定位库,微秒的查询时间:

实现步骤:

        访问官网github地址:https://github.com/lionsoul2014/ip2region

 找到data目录下的:ip2region.xdb文件下载下来

 把ip2region.xdb文件放在resources目录下

在模块中引入maven依赖

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

获取归属地:

private Searcher searcher;

@Override
    public String getIpAddress(String ip){
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {
            return "|||局域网ip";

        }
        if (searcher == null) {
            try {
                File file = ResourceUtils.getFile("classpath:db/data_ip2region.xdb");
                String dbPath = file.getPath();
                searcher = Searcher.newWithFileOnly(dbPath);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String region = null;
        String errorMessage = null;
        try {
            region = searcher.search(ip);
        } catch (Exception e) {
            errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.length() > 256) {
                errorMessage = errorMessage.substring(0, 256);
            }
            e.printStackTrace();
        }
        // 输出 region
        System.out.println(region);
        return region;
    }

        这里Searcher引用的是仓库里面的检索方法,到这里就完成了可以获取到ip对应的归属地。

调用方法后运行结果如下

注意!!!! 本地是没问题的 如果打成jar包放在linux服务器上会读取不到

解决办法:

        

    public String getIpCity(String ip) {
        if ("127.0.0.1".equals(ip) || ip.startsWith("192.168")) {
            return "|||局域网ip";

        }
        if (searcher == null) {
            try {
                //本地环境需要加上 classpath:
//File file = ResourceUtils.getFile("classpath:db/data_ip2region.xdb");
                File file = ResourceUtils.getFile("db/data_ip2region.xdb");
                String dbPath = file.getPath();
                searcher = Searcher.newWithFileOnly(dbPath);
                   //这里通过流获取 解决jar包无法读取文件问题
                ResponseEntity<byte[]> test = test("db/data_ip2region.xdb");
                searcher = Searcher.newWithBuffer(test.getBody());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String region = null;
        String errorMessage = null;
        try {
            region = searcher.search(ip);
        } catch (Exception e) {
            errorMessage = e.getMessage();
            if (errorMessage != null && errorMessage.length() > 256) {
                errorMessage = errorMessage.substring(0, 256);
            }
            e.printStackTrace();
        }
        // 输出 region
        return region;
    }

    public static ResponseEntity<byte[]> test(String templateName) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource(templateName);
        String filename = classPathResource.getFilename();
        @Cleanup InputStream inputStream = classPathResource.getInputStream();
        byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
        String fileName = new String(filename.getBytes("UTF-8"), "iso-8859-1");// 为了解决中文名称乱码问题
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);
        return new ResponseEntity<>(bytes, headers, HttpStatus.CREATED);
    }

        至于什么是Ip2region 官网上面有介绍这里就不多介绍了

  • 4
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
您好,要根据 IP 地址获取归属地,可以使用 Java 自带的 `InetAddress` 类和 `ip138` 等在线查询工具。 以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class IPUtils { /** * 根据 IP 地址获取归属地 * * @param ip IP 地址 * @return 归属地字符串 * @throws IOException */ public static String getIpAddress(String ip) throws IOException { InetAddress inetAddress = InetAddress.getByName(ip); String hostAddress = inetAddress.getHostAddress(); String url = "http://www.ip138.com/ips138.asp?ip=" + hostAddress + "&action=2"; URLConnection connection = new URL(url).openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "gbk")); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); String content = stringBuilder.toString(); String regex = "<li>本站主数据:(.*?)</li>"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(content); if (matcher.find()) { return matcher.group(1); } return "未知"; } public static void main(String[] args) throws IOException { String ip = "113.96.208.44"; String address = getIpAddress(ip); System.out.println(ip + " 的归属地是:" + address); } } ``` 该代码通过 `InetAddress` 类获取 IP 地址的主机名,然后构造查询 URL,请求 IP138 等在线查询工具获取归属地信息,并使用正则表达式从响应内容中提取出归属地。注意需要设置读取响应的字符编码为 GBK。 需要注意的是,该方法仅供学习和参考,实际应用中可能存在 IP 地址和归属地不匹配的情况,也可能存在在线查询工具挂掉或者响应超时的情况,需要根据实际情况进行处理。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值