当前位置: 首页 > news >正文

获取客户端请求IP及IP所属城市

添加pom依赖

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

public class IpUtil {
    private static Searcher searcher;
    private static final String DEFAULT_UNKNOWN="unknown";
    private static final int IP_MIN_LENGTH=0;
    static{
        try {
            ResponseEntity<byte[]> entity= buildResponseEntity("ip2region.xdb");
            searcher = Searcher.newWithBuffer(entity.getBody());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String getIpAddress(HttpServletRequest request) {
        String ip = DEFAULT_UNKNOWN;
        try {
            ip = request.getHeader("X-Forwarded-For");
            if (ip == null || ip.length() == IP_MIN_LENGTH || DEFAULT_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == IP_MIN_LENGTH || DEFAULT_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == IP_MIN_LENGTH || DEFAULT_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == IP_MIN_LENGTH || DEFAULT_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == IP_MIN_LENGTH || DEFAULT_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            // 处理多级代理情况
            if (StringUtils.isNotBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
                int index = ip.indexOf(",");
                if (index > 0) {
                    return ip.substring(0, index);
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return ip;
    }

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

        if (searcher == null) {
            return "...";
        }
        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();
        }
        return region;
    }

    public static ResponseEntity<byte[]> buildResponseEntity(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<byte[]>(bytes, headers, HttpStatus.CREATED);
    }

    public static void main(String[] args){
        System.out.println("********/"+ getCityByIp("61.154.231.236"));
    }
}

完整代码:https://download.csdn.net/download/paj123456789/88478095

http://www.lryc.cn/news/212856.html

相关文章:

  • 【洛谷 P1106】删数问题 题解(贪心+字符串)
  • 【Python · PyTorch】线性代数 微积分
  • 建模和图表工具:Software Ideas Modeler Crack
  • Android开发,车载通讯应用——binder通讯原理解析
  • [算法]求n!在m进制下末尾有多少个0
  • mysql之用户管理、权限管理、密码管理
  • 图情档核心期刊 | 北大核心、CSSCI、CSCD
  • Mac上具好用的屏幕录像工具(Omi录屏专家)Screen Recorder By Omi Mac 下载安装详细教程
  • 牛客网刷题-(8)
  • oracle 重启步骤及踩坑经验
  • 处理mysql数据量大查询缓慢问题(最少百万才有差别)
  • element-plus走马灯不显示
  • 【精】UML及软件管理工具汇总
  • 【uniapp+vue3】scroll-view实现纵向自动滚动及swiper实现纵向自动滚动
  • this.refs[‘tagInput‘].refs.input.focus()和this.$refs[‘tagInput‘].focus()区别
  • 电脑硬件坏了,如何维修?
  • elementplus日期时间选择器组件显示很窄
  • 第三方软件测评选择远程测试好还是现场测试好?
  • HTTPS协议:保障网络安全的加密通信协议
  • C++设计模式_21_Iterator 迭代器(理解;面向对象的迭代器已过时;C++中使用泛型编程的方式实现)
  • 有一个 3*4 的矩阵,找出其中值最大的元素,及其行列号
  • 磁盘的命令
  • 一张图讲清楚业务稳定性要如何做:SRE体系化稳定性方案
  • 安卓端GB28181设备接入模块如何实现实时位置订阅(MobilePosition)
  • 11.与JavaScript深入交流-[js一篇通]
  • Ubuntu 搭建 DHCP ivp6 server 步骤
  • 分享大数据分析师前景怎么样? 从事行业有哪些?
  • 通过wordpress能搭建有影响力的帮助中心
  • word页脚设置,页脚显示第几页共有几页设置步骤
  • C语言实现斐波那契数列的多种方法