• 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
  • 相关阅读:
    变参宏 __VA_ARGS__
    预处理中的 # 和 ##
    strlen与sizeof异同
    .vimrc
    sudo:有效用户 ID 不是 0,sudo 属于 root 并设置了 setuid 位吗
    远程ssh登陆时报错:/bin/bash: Permission denied
    Excel中VBA进行插入列、格式化、排序
    ORACLE发送带附件邮件的二三事之一
    Windows Server 2008 双网卡同时上内外网 不能正常使用
    VMWARE修改CPUID
  • 原文地址:https://www.cnblogs.com/coderxiaobai/p/15125233.html
Copyright © 2020-2023  润新知