get Client IP from HttpServletRequest - Java Servlet JSP

Java examples for Servlet JSP:Servlet

Description

get Client IP from HttpServletRequest

Demo Code


import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;

public class Main{
    public static String getClientIP(HttpServletRequest request) {
        String ip;//from  ww  w. j  a v a2  s  .c  o  m
        ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0) {
            ip = request.getHeader("http-x-forwarded-for");
            if (ip == null || ip.length() == 0) {
                ip = request.getHeader("remote-addr");
                if (ip == null || ip.length() == 0) {
                    ip = request.getRemoteAddr();
                }
            }
        }
        return ip;
    }
}

Related Tutorials