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