zoukankan      html  css  js  c++  java
  • java获取登录ip和地址

    //获取HttpServletRequest对象
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    
    
    /**
    * 获取登录用户的IP地址
    *
    * @param request HttpServletRequest
    * @return String
    */
    public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
    ip = request.getRemoteAddr();
    }
    if ("0:0:0:0:0:0:0:1".equals(ip)) {
    ip = "127.0.0.1";
    }
    if (ip.split(",").length > 1) {
    ip = ip.split(",")[0];
    }
    return ip;
    }

    /**
    * 通过IP获取地址
    *
    * @param ip http://freeapi.ipip.net/ip
    * @return String
    */
    public static String getIpInfo(String ip) {
    if ("127.0.0.1".equals(ip)) {
    ip = "127.0.0.1";
    }
    String info = "";
    try {
    URL url = new URL("http://freeapi.ipip.net/" + ip);
    HttpURLConnection htpcon = (HttpURLConnection) url.openConnection();
    htpcon.setRequestMethod("GET");
    htpcon.setDoOutput(true);
    htpcon.setDoInput(true);
    htpcon.setUseCaches(false);
    InputStream in = htpcon.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
    StringBuilder temp = new StringBuilder();
    String line = bufferedReader.readLine();
    while (line != null) {
    temp.append(line).append(" ");
    line = bufferedReader.readLine();
    }
    bufferedReader.close();
    JSONArray jsonArray = JSONObject.parseArray(temp.toString());
    info = info + jsonArray.get(0) + jsonArray.get(1) + jsonArray.get(2) + jsonArray.get(3) + jsonArray.get(4);
    } catch (IOException e) {
    e.printStackTrace();
    }
    return info;
    }
     

    注意:http://freeapi.ipip.net/  该接口有多次后拒绝请求问题,不建议使用,可使用

    ip2region      
    http://whois.pconline.com.cn
  • 相关阅读:
    C#中 ??、 ?、 ?: 、?.、?[ ] 问号各组合含义
    ASP.NET Core MVC配置差异(3.0和2.X)
    vs code搭建Django环境
    解决真机编译出现System.DllNotFoundException: 'libmono-native.so'错误都方法
    选择器
    Web.Config配置
    读Xamarin文档记录
    【前端自动化】Gulp的使用(一):安装gulp
    关于angularJS绑定数据时自动转义html标签
    【记录】两年程序生涯的点滴与反思
  • 原文地址:https://www.cnblogs.com/coderxiaobai/p/15125233.html
Copyright © 2011-2022 走看看