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
  • 相关阅读:
    【LOJ】 #2015. 「SCOI2016」妖怪
    【LOJ】#2016. 「SCOI2016」美味
    【LOJ】 #2008. 「SCOI2015」小凸想跑步
    【LOJ】#2007. 「SCOI2015」国旗计划
    【LOJ】#2006. 「SCOI2015」小凸玩矩阵
    【LOJ】#2172. 「FJOI2016」所有公共子序列问题
    【LOJ】#2173. 「FJOI2016」建筑师
    【LOJ】#2174. 「FJOI2016」神秘数
    【LOJ】#2280. 「FJOI2017」矩阵填数
    【洛谷】P4585 [FJOI2015]火星商店问题
  • 原文地址:https://www.cnblogs.com/coderxiaobai/p/15125233.html
Copyright © 2011-2022 走看看