Skip to content

Instantly share code, notes, and snippets.

@nioe
Last active January 30, 2024 20:40
Show Gist options
  • Select an option

  • Save nioe/11477264 to your computer and use it in GitHub Desktop.

Select an option

Save nioe/11477264 to your computer and use it in GitHub Desktop.
Get remote IP from HttpServletRequest
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;
}
}
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);
}
}
@gmarziou

gmarziou commented Apr 7, 2016

Copy link
Copy Markdown

X-Forwarded-For is a multiple value header, if user goes through 2 proxies, header will contain 2 IP addresses separated by commas.

@edwanyoike

Copy link
Copy Markdown

thanks man

@romanoffs

Copy link
Copy Markdown

Thank you)

@CasperOm

CasperOm commented Jan 20, 2021

Copy link
Copy Markdown

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