servlet get IP from HttpServletRequest - Java javax.servlet.http

Java examples for javax.servlet.http:HttpServletRequest

Description

servlet get IP from HttpServletRequest

Demo Code


import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    public static String getIP(String ip, HttpServletRequest request) {
        if ("self".equals(ip) || "current".equals(ip) || isTrivial(ip)) {
            return getTrueClientIPFromXFF(request);
        } else {/*ww w .  j a  v a2  s  . c o m*/
            return ip;
        }

    }
    /**
     * Returns true if two strings are considered equal, false
     * otherwise
     *
     * @param s1 the first string
     * @param s2 the second string
     * @return the equality of the two Strings
     */
    @SuppressWarnings({ "StringEquality" })
    public static boolean equals(String s1, String s2) {
        return s1 == s2 || s1 != null && s1.equals(s2);
    }
    /**
     * Returns true if the specified string is a trivial string.
     * A trivial string is either null or "" after trimming
     *
     * @param s String to compare
     * @return true if the specified string is trivial, false otherwise
     */
    public static boolean isTrivial(String s) {
        return s == null || "".equals(s.trim());
    }
    public static String getTrueClientIPFromXFF(HttpServletRequest request) {
        String xff = request.getHeader("X-Forwarded-For");
        if (isNonTrivial(xff)) {
            xff = xff.trim();
            int index = xff.indexOf(",");
            if (index > 0) {
                return xff.substring(0, index).trim();
            } else {
                return xff;
            }

        }
        return request.getRemoteAddr();
    }
    /**
     * Returns true if the specified string is a non trivial string.
     * A non trivial string is neither null nor "" after trimming
     *
     * @param s String to compare
     * @return true if the specified string is non trivial, false otherwise
     */
    public static boolean isNonTrivial(String s) {
        return s != null && !"".equals(s.trim());
    }
}

Related Tutorials