1. 程式人生 > >Java根據HttpServletRequest請求獲取伺服器的IP地址

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地址。