zoukankan      html  css  js  c++  java
  • java 获取真实ip地址

    /**
         * 获取真实ip地址
         * @param request
         * @return
         */
        public static String getIpAddress(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.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        }

    public static String getIpAddress() {
            try {
                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                InetAddress ip = null;
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                    if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                        continue;
                    } else {
                        Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                        while (addresses.hasMoreElements()) {
                            ip = addresses.nextElement();
                            if (ip != null && ip instanceof Inet4Address) {
                                return ip.getHostAddress();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                System.err.println("IP地址获取失败" + e.toString());
            }
            return "";
        }
    
    
    
     

    直接贴代码

  • 相关阅读:
    serialVersionUID作用
    为什么要使用SLF4J而不是Log4J
    认识Log4j
    Java解析xml文件四种方式
    数据结构之R进制转换
    栈的压入、弹出序列
    中间件学习之RMI+JDBC远端数据库的访问
    Linux程序设计综合训练之简易Web服务器
    Html5笔记之小结
    PhoneGap + Dreamweaver 5.5 无法在模拟器中打开的问题
  • 原文地址:https://www.cnblogs.com/weibanggang/p/11995578.html
Copyright © 2011-2022 走看看