Last active
January 30, 2024 20:40
-
-
Save nioe/11477264 to your computer and use it in GitHub Desktop.
Get remote IP from HttpServletRequest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum HttpHeader { | |
AUTHORIZATION("Authorization"), | |
AUTHENTICATION_TYPE_BASIC("Basic"), | |
X_AUTH_TOKEN("X-AUTH-TOKEN"), | |
WWW_Authenticate("WWW-Authenticate"), | |
X_FORWARDED_FOR("X-Forwarded-For"), | |
PROXY_CLIENT_IP("Proxy-Client-IP"), | |
WL_PROXY_CLIENT_IP("WL-Proxy-Client-IP"), | |
HTTP_CLIENT_IP("HTTP_CLIENT_IP"), | |
HTTP_X_FORWARDED_FOR("HTTP_X_FORWARDED_FOR"); | |
private String key; | |
private HttpHeader(String key) { | |
this.key = key; | |
} | |
public String key() { | |
return this.key; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.servlet.http.HttpServletRequest; | |
import static ch.exq.triplog.server.util.http.HttpHeader.*; | |
public class RemoteIpHelper { | |
private static final String UNKNOWN = "unknown"; | |
public static String getRemoteIpFrom(HttpServletRequest request) { | |
String ip = null; | |
int tryCount = 1; | |
while (!isIpFound(ip) && tryCount <= 6) { | |
switch (tryCount) { | |
case 1: | |
ip = request.getHeader(X_FORWARDED_FOR.key()); | |
break; | |
case 2: | |
ip = request.getHeader(PROXY_CLIENT_IP.key()); | |
break; | |
case 3: | |
ip = request.getHeader(WL_PROXY_CLIENT_IP.key()); | |
break; | |
case 4: | |
ip = request.getHeader(HTTP_CLIENT_IP.key()); | |
break; | |
case 5: | |
ip = request.getHeader(HTTP_X_FORWARDED_FOR.key()); | |
break; | |
default: | |
ip = request.getRemoteAddr(); | |
} | |
tryCount++; | |
} | |
return ip; | |
} | |
private static boolean isIpFound(String ip) { | |
return ip != null && ip.length() > 0 && !UNKNOWN.equalsIgnoreCase(ip); | |
} | |
} |
thanks man
Thank you)
Hi, request.getRemoteAddr() gives me private ip address instead of public ip address. How we get Public IP?
Any suggestions would be appreciated.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
X-Forwarded-For is a multiple value header, if user goes through 2 proxies, header will contain 2 IP addresses separated by commas.