zoukankan      html  css  js  c++  java
  • Java根据HttpServletRequest请求获取服务器的IP地址

      以下总结了两种根据HttpServletRequest请求获取发出请求浏览器客户端所在服务器的IP地址方法:

    代码:

    import javax.servlet.http.HttpServletRequest;
    
    /**
     * 根据HttpServletRequest请求获取发出请求浏览器客户端所在服务器的IP地址
     * @author 【】
     *
     */
    public class IPUtil {
    	/*
    	 * 第一种方法
    	 */
    	public 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();
    		}
    		return ip;
    	}
    	
    	/*
    	 * 第二种方法
    	 */
    	public String getIP(HttpServletRequest request) {
    		String remoteAddr = request.getRemoteAddr();  
    		String forwarded = request.getHeader("X-Forwarded-For");  
    		String realIp = request.getHeader("X-Real-IP");  
    		String ip = null;  
    		if (realIp == null) {  
    		    if (forwarded == null) {  
    		        ip = remoteAddr;  
    		    } else {  
    		        ip = remoteAddr + "/" + forwarded.split(",")[0];  
    		    }  
    		} else {  
    		    if (realIp.equals(forwarded)) {  
    		        ip = realIp;  
    		    } else {  
    		        if(forwarded != null){  
    		            forwarded = forwarded.split(",")[0];  
    		        }  
    		        ip = realIp + "/" + forwarded;  
    		    }  
    		}
    		return ip;
    	}
    }
    

       注:如果在本机访问服务时(服务器和客户端都在同一台电脑上,例如用localhost访问的时候就会出现),获取的IP值会为“0:0:0:0:0:0:0:1”,这是IPV6的IP。如果本机通过localhost、127.0.0.1和本机真实地址访问时获取到的ip也有区别,把localhost换成127.0.0.1或本机真实地址就变成了IPV4,即所需的IP地址。

  • 相关阅读:
    Directx 3D编程实例:多个3D球的综合Directx实例
    利用组策略禁用Oultook 各个版本的缓存模式!
    node-mongo-native1.3.19连接mongo的最优方法
    BT5之网络配置
    BT5之配置笔记
    Linux常用命令大全
    Linux下的基本网络配置
    SQLMAP系列教程
    重燃你的PHP安全分析之火
    Metasploit渗透测试魔鬼训练营
  • 原文地址:https://www.cnblogs.com/Big-Boss/p/9999361.html
Copyright © 2011-2022 走看看