IT源码网

java 获取真实ip地址讲解

luoye 2021年02月13日 编程语言 183 0
/** 
     * 获取真实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 ""; 
    }
 
 

 

 

直接贴代码

发布评论
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

java get请求带参数报错 java.io.IOException: Server returned HTTP response code: 400 for URL讲解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。