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 栈和堆的区别
    ubuntu 12.10 禁用触摸板
    完美解决 linux sublime 中文无法输入
    gdb 断点调试C程序
    归并排序
    算法效率表示
    sublime -text 删除已安装插件
    MSSQL数据库表索引碎片整理优化性能
    Rdlc报表出现空白页解决方法
    RDLC报表:每页显示N条记录
  • 原文地址:https://www.cnblogs.com/coderxiaobai/p/15125233.html
Copyright © 2011-2022 走看看